Java设计模式精讲

时光旅者 2020-04-25 ⋅ 13 阅读

设计模式是一种被广泛应用于软件开发中的解决问题的方法论。它们可以帮助我们写出高质量、易于维护和可扩展的代码。在Java开发中,设计模式是必不可少的知识点。本文将为您介绍几种常用的Java设计模式。

1. 创建型模式

创建型模式主要关注如何实例化一个对象。它们有助于隐藏对象的创建细节,从而提供更高的灵活性。

1.1. 工厂模式(Factory Pattern)

工厂模式通过使用工厂方法来创建对象,而不是直接调用构造函数。这样,我们可以隐藏创建具体对象的细节,并根据需求提供不同类型的对象。

// 定义产品接口
public interface Product {
    void doSomething();
}

// 具体产品类1
public class ConcreteProduct1 implements Product {
    @Override
    public void doSomething() {
        System.out.println("ConcreteProduct1 do something");
    }
}

// 具体产品类2
public class ConcreteProduct2 implements Product {
    @Override
    public void doSomething() {
        System.out.println("ConcreteProduct2 do something");
    }
}

// 工厂类
public class ProductFactory {
    public Product createProduct(String type) {
        if (type.equals("Type1")) {
            return new ConcreteProduct1();
        } else if (type.equals("Type2")) {
            return new ConcreteProduct2();
        }
        return null;
    }
}

// 测试代码
public class Main {
    public static void main(String[] args) {
        ProductFactory factory = new ProductFactory();

        Product product1 = factory.createProduct("Type1");
        product1.doSomething();

        Product product2 = factory.createProduct("Type2");
        product2.doSomething();
    }
}

1.2. 单例模式(Singleton Pattern)

单例模式用于保证一个类只有一个实例,并提供一个全局访问点来获取该实例。

public class Singleton {
    private static Singleton instance;

    private Singleton() { }

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

    public void doSomething() {
        System.out.println("Singleton do something");
    }
}

// 测试代码
public class Main {
    public static void main(String[] args) {
        Singleton singleton = Singleton.getInstance();
        singleton.doSomething();
    }
}

1.3. 建造者模式(Builder Pattern)

建造者模式用于通过一系列步骤来创建复杂对象,而不是一次性地创建它们。它与工厂模式的区别在于:工厂模式关注创建单个对象,而建造者模式关注创建一个步骤复杂且具有多个属性的对象。

// 产品类
public class Product {
    private String property1;
    private String property2;
    private int property3;

    public String getProperty1() {
        return property1;
    }

    public void setProperty1(String property1) {
        this.property1 = property1;
    }

    public String getProperty2() {
        return property2;
    }

    public void setProperty2(String property2) {
        this.property2 = property2;
    }

    public int getProperty3() {
        return property3;
    }

    public void setProperty3(int property3) {
        this.property3 = property3;
    }
}

// 建造者类
public class ProductBuilder {
    private Product product;

    public ProductBuilder() {
        this.product = new Product();
    }

    public ProductBuilder setProperty1(String property1) {
        product.setProperty1(property1);
        return this;
    }

    public ProductBuilder setProperty2(String property2) {
        product.setProperty2(property2);
        return this;
    }

    public ProductBuilder setProperty3(int property3) {
        product.setProperty3(property3);
        return this;
    }

    public Product build() {
        return product;
    }
}

// 测试代码
public class Main {
    public static void main(String[] args) {
        Product product = new ProductBuilder()
                            .setProperty1("Property1")
                            .setProperty2("Property2")
                            .setProperty3(10)
                            .build();
    }
}

2. 结构型模式

结构型模式关注如何构建组件和类,并提供对象之间的关系,以便构成更大的结构。

2.1. 适配器模式(Adapter Pattern)

适配器模式用于将一个类的接口转换成客户端所期望的另一个接口。它可以让原本由于接口不兼容而不能一起工作的类可以一起工作。

// 原始接口
public interface OriginalInterface {
    void methodA();
    void methodB();
}

// 原始类
public class OriginalClass implements OriginalInterface {
    @Override
    public void methodA() {
        System.out.println("OriginalClass methodA");
    }

    @Override
    public void methodB() {
        System.out.println("OriginalClass methodB");
    }
}

// 适配器接口
public interface AdapterInterface {
    void methodX();
    void methodY();
}

// 适配器类
public class AdapterClass implements AdapterInterface {
    private OriginalInterface original;

    public AdapterClass(OriginalInterface original) {
        this.original = original;
    }

    @Override
    public void methodX() {
        original.methodA();
    }

    @Override
    public void methodY() {
        original.methodB();
    }
}

// 测试代码
public class Main {
    public static void main(String[] args) {
        OriginalInterface original = new OriginalClass();

        AdapterInterface adapter = new AdapterClass(original);
        adapter.methodX();
        adapter.methodY();
    }
}

2.2. 组合模式(Composite Pattern)

组合模式允许我们将对象组合成树形结构,以表示“整体-部分”的层次结构。通过使用递归算法,我们可以轻松地处理整个结构,而不必关心其具体的组成部分。

// 组件接口
public interface Component {
    void doSomething();
}

// 叶子组件类
public class Leaf implements Component {
    @Override
    public void doSomething() {
        System.out.println("Leaf do something");
    }
}

// 容器组件类
public class Composite implements Component {
    private List<Component> children = new ArrayList<>();

    public void addComponent(Component component) {
        children.add(component);
    }

    public void removeComponent(Component component) {
        children.remove(component);
    }

    @Override
    public void doSomething() {
        System.out.println("Composite do something");

        for (Component component : children) {
            component.doSomething();
        }
    }
}

// 测试代码
public class Main {
    public static void main(String[] args) {
        Component leaf1 = new Leaf();
        Component leaf2 = new Leaf();

        Composite composite = new Composite();
        composite.addComponent(leaf1);
        composite.addComponent(leaf2);

        composite.doSomething();
    }
}

2.3. 装饰器模式(Decorator Pattern)

装饰器模式允许我们在不改变已有对象的前提下,动态地给它们添加额外的功能。

// 原始接口
public interface Component {
    void doSomething();
}

// 原始类
public class ConcreteComponent implements Component {
    @Override
    public void doSomething() {
        System.out.println("ConcreteComponent do something");
    }
}

// 装饰器类
public class Decorator implements Component {
    private Component component;

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

    @Override
    public void doSomething() {
        component.doSomething();
        System.out.println("Decorator do something");
    }
}

// 测试代码
public class Main {
    public static void main(String[] args) {
        Component component = new ConcreteComponent();
        component = new Decorator(component);

        component.doSomething();
    }
}

3. 行为型模式

行为型模式关注对象之间的职责分配和协作。

3.1. 策略模式(Strategy Pattern)

策略模式定义了一组算法,将每个算法封装起来,并使它们之间可以互换。这样,可以根据不同的上下文选择不同的策略。

// 策略接口
public interface Strategy {
    void doSomething();
}

// 策略类1
public class ConcreteStrategy1 implements Strategy {
    @Override
    public void doSomething() {
        System.out.println("ConcreteStrategy1 do something");
    }
}

// 策略类2
public class ConcreteStrategy2 implements Strategy {
    @Override
    public void doSomething() {
        System.out.println("ConcreteStrategy2 do something");
    }
}

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

    public void setStrategy(Strategy strategy) {
        this.strategy = strategy;
    }

    public void doSomething() {
        strategy.doSomething();
    }
}

// 测试代码
public class Main {
    public static void main(String[] args) {
        Context context = new Context();

        Strategy strategy1 = new ConcreteStrategy1();
        context.setStrategy(strategy1);
        context.doSomething();

        Strategy strategy2 = new ConcreteStrategy2();
        context.setStrategy(strategy2);
        context.doSomething();
    }
}

3.2. 观察者模式(Observer Pattern)

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

// 主题接口
public interface Subject {
    void registerObserver(Observer observer);
    void removeObserver(Observer observer);
    void notifyObservers();
}

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

// 主题类
public class ConcreteSubject implements Subject {
    private List<Observer> observers = new ArrayList<>();

    @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();
        }
    }
}

// 观察者类
public class ConcreteObserver implements Observer {
    @Override
    public void update() {
        System.out.println("ConcreteObserver received update");
    }
}

// 测试代码
public class Main {
    public static void main(String[] args) {
        Subject subject = new ConcreteSubject();
        Observer observer = new ConcreteObserver();

        subject.registerObserver(observer);
        subject.notifyObservers();
    }
}

3.3. 状态模式(State Pattern)

状态模式允许一个对象在内部状态发生变化时改变其行为。它将对象状态封装成单独的状态类,以实现代码的解耦和复用。

// 状态接口
public interface State {
    void handle();
}

// 具体状态类1
public class ConcreteState1 implements State {
    @Override
    public void handle() {
        System.out.println("ConcreteState1 handle");
    }
}

// 具体状态类2
public class ConcreteState2 implements State {
    @Override
    public void handle() {
        System.out.println("ConcreteState2 handle");
    }
}

// 环境类
public class Context {
    private State state;

    public void setState(State state) {
        this.state = state;
    }

    public void doSomething() {
        state.handle();
    }
}

// 测试代码
public class Main {
    public static void main(String[] args) {
        Context context = new Context();

        State state1 = new ConcreteState1();
        context.setState(state1);
        context.doSomething();

        State state2 = new ConcreteState2();
        context.setState(state2);
        context.doSomething();
    }
}

设计模式是一项重要的软件开发技术,在Java中有许多成熟的设计模式可供选择。上述介绍的只是其中的几种常见的设计模式,希望能够帮助您在开发过程中应用设计模式解决问题。通过使用适当的设计模式,可以提高代码质量和可维护性,使软件更加容易扩展和适应需求的变化。


全部评论: 0

    我有话说: