Java常见设计模式入门与实践

发布于:2024-06-16 ⋅ 阅读:(21) ⋅ 点赞:(0)

设计模式是软件开发中被反复应用的、为解决特定问题而总结出的最佳实践。它们提供了开发可重用、灵活和高效软件系统的方法。在Java中,设计模式可以帮助开发者编写更高质量的代码。以下是Java中一些常用设计模式的入门介绍及其实践示例。

1. 单例模式 (Singleton Pattern)

单例模式确保一个类只有一个实例,并提供一个全局访问点。

示例代码
public class Singleton {
    private static Singleton instance;

    private Singleton() {
        // 私有构造函数防止实例化
    }

    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

2. 工厂模式 (Factory Pattern)

工厂模式定义一个创建对象的接口,但让子类决定实例化哪一个类。工厂模式使一个类的实例化延迟到其子类。

示例代码
// 产品接口
public interface Product {
    void use();
}

// 具体产品类
public class ConcreteProduct implements Product {
    @Override
    public void use() {
        System.out.println("Using ConcreteProduct");
    }
}

// 工厂类
public class Factory {
    public Product createProduct() {
        return new ConcreteProduct();
    }
}

// 客户端代码
public class Main {
    public static void main(String[] args) {
        Factory factory = new Factory();
        Product product = factory.createProduct();
        product.use();
    }
}

3. 观察者模式 (Observer Pattern)

观察者模式定义了对象之间的一对多依赖,当一个对象改变状态时,它的所有依赖者都会收到通知并自动更新。

示例代码
import java.util.ArrayList;
import java.util.List;

// 观察者接口
interface Observer {
    void update(String message);
}

// 具体观察者类
class ConcreteObserver implements Observer {
    private String name;

    public ConcreteObserver(String name) {
        this.name = name;
    }

    @Override
    public void update(String message) {
        System.out.println(name + " received: " + message);
    }
}

// 被观察者接口
interface Subject {
    void registerObserver(Observer observer);
    void removeObserver(Observer observer);
    void notifyObservers();
}

// 具体被观察者类
class ConcreteSubject implements Subject {
    private List<Observer> observers = new ArrayList<>();
    private String message;

    public void setMessage(String message) {
        this.message = message;
        notifyObservers();
    }

    @Override
    public void registerObserver(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void removeObserver(Observer observer) {
        observers.remove(observer);
    }

    @Override
    public void notifyObservers() {
        for (Observer observer : observers) {
            observer.update(message);
        }
    }
}

// 客户端代码
public class Main {
    public static void main(String[] args) {
        ConcreteSubject subject = new ConcreteSubject();

        Observer observer1 = new ConcreteObserver("Observer 1");
        Observer observer2 = new ConcreteObserver("Observer 2");

        subject.registerObserver(observer1);
        subject.registerObserver(observer2);

        subject.setMessage("Hello, Observers!");
    }
}

4. 策略模式 (Strategy Pattern)

策略模式定义了算法家族,并且使它们之间可以互相替换。策略模式让算法的变化独立于使用算法的客户。

示例代码
// 策略接口
interface Strategy {
    int doOperation(int num1, int num2);
}

// 具体策略类
class Addition implements Strategy {
    @Override
    public int doOperation(int num1, int num2) {
        return num1 + num2;
    }
}

class Subtraction implements Strategy {
    @Override
    public int doOperation(int num1, int num2) {
        return num1 - num2;
    }
}

// 上下文类
class Context {
    private Strategy strategy;

    public Context(Strategy strategy) {
        this.strategy = strategy;
    }

    public int executeStrategy(int num1, int num2) {
        return strategy.doOperation(num1, num2);
    }
}

// 客户端代码
public class Main {
    public static void main(String[] args) {
        Context context = new Context(new Addition());
        System.out.println("10 + 5 = " + context.executeStrategy(10, 5));

        context = new Context(new Subtraction());
        System.out.println("10 - 5 = " + context.executeStrategy(10, 5));
    }
}

5. 装饰者模式 (Decorator Pattern)

装饰者模式动态地将责任附加到对象上。装饰者提供了比继承更有弹性的替代方案。

示例代码
// 组件接口
interface Component {
    void operation();
}

// 具体组件类
class ConcreteComponent implements Component {
    @Override
    public void operation() {
        System.out.println("ConcreteComponent operation");
    }
}

// 装饰者抽象类
abstract class Decorator implements Component {
    protected Component component;

    public Decorator(Component component) {
        this.component = component;
    }

    public void operation() {
        component.operation();
    }
}

// 具体装饰者类
class ConcreteDecorator extends Decorator {
    public ConcreteDecorator(Component component) {
        super(component);
    }

    @Override
    public void operation() {
        super.operation();
        addedBehavior();
    }

    private void addedBehavior() {
        System.out.println("ConcreteDecorator added behavior");
    }
}

// 客户端代码
public class Main {
    public static void main(String[] args) {
        Component component = new ConcreteComponent();
        Component decorator = new ConcreteDecorator(component);
        decorator.operation();
    }
}

总结

以上是一些常用设计模式的入门介绍及其Java实现示例。掌握这些设计模式有助于编写更加可维护、灵活和高效的代码。设计模式不仅仅是代码模板,更是一种思维方式,可以帮助开发者在面临复杂问题时找到最佳解决方案。通过不断的学习和实践,可以更好地理解和应用这些设计模式。