设计模式是软件开发中为了提高代码的可重用性和可维护性,解决特定问题而总结出的最佳实践。在Java中,有23种经典的设计模式,大致可以分为三类:创建型、结构型和行为型。

创建型模式

  1. 单例模式(Singleton Pattern)
    单例模式确保一个类只有一个实例,并提供一个全局访问点。
    ```java public class Singleton { private static Singleton instance;

    private Singleton() {}

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

  2. 工厂方法模式(Factory Method Pattern)
    工厂方法模式定义一个创建对象的接口,让子类决定实例化哪一个类。
    ```java interface Product { void use(); }

class ConcreteProductA implements Product { public void use() { System.out.println("使用产品A"); } }

class ProductFactory { public Product createProduct(String type) { if (type.equals("A")) { return new ConcreteProductA(); } return null; } } ```

  1. 抽象工厂模式(Abstract Factory Pattern)
    抽象工厂模式提供一个创建相关或相互依赖对象的接口。
    ```java interface AbstractFactory { ProductA createProductA(); ProductB createProductB(); }

class ConcreteFactory1 implements AbstractFactory { public ProductA createProductA() { return new ProductA1(); } public ProductB createProductB() { return new ProductB1(); } } ```

  1. 建造者模式(Builder Pattern)
    建造者模式用于构建一个复杂对象的各个部分。
    ```java class Product { private String partA; private String partB; // getters and setters }

class ProductBuilder { private Product product = new Product();

   public ProductBuilder buildPartA(String partA) {
       product.setPartA(partA);
       return this;
   }

   public ProductBuilder buildPartB(String partB) {
       product.setPartB(partB);
       return this;
   }

   public Product build() {
       return product;
   }

} ```

  1. 原型模式(Prototype Pattern)
    原型模式用于通过复制现有的实例来创建新实例。
    ```java class Prototype implements Cloneable { private String attribute;

    @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } } ```

结构型模式

  1. 适配器模式(Adapter Pattern)
    适配器模式使不兼容的接口可以协同工作。
    ```java class Adaptee { void specificRequest() { System.out.println("特定请求"); } }

interface Target { void request(); }

class Adapter implements Target { private Adaptee adaptee;

   public Adapter(Adaptee adaptee) {
       this.adaptee = adaptee;
   }

   @Override
   public void request() {
       adaptee.specificRequest();
   }

} ```

  1. 桥接模式(Bridge Pattern)
    桥接模式将抽象部分与其实现部分分离,使它们可以独立变化。
    ```java interface Implementor { void operation(); }

class ConcreteImplementorA implements Implementor { public void operation() { System.out.println("实现A"); } }

abstract class Abstraction { protected Implementor implementor;

   public Abstraction(Implementor implementor) {
       this.implementor = implementor;
   }

   abstract void operation();

} ```

  1. 组合模式(Composite Pattern)
    组合模式将对象组合成树形结构以表示部分和整体的层次结构。
    ```java interface Component { void operation(); }

class Leaf implements Component { public void operation() { System.out.println("叶子节点"); } }

class Composite implements Component { private List children = new ArrayList<>();

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

   public void operation() {
       for (Component child : children) {
           child.operation();
       }
   }

} ```

  1. 装饰者模式(Decorator Pattern)
    装饰者模式允许向现有对象添加新功能。
    ```java interface Component { void operation(); }

class ConcreteComponent implements Component { public void operation() { System.out.println("标准功能"); } }

class Decorator implements Component { protected Component component;

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

   public void operation() {
       component.operation();
       System.out.println("增加的功能");
   }

} ```

  1. 外观模式(Facade Pattern)
    外观模式为子系统提供一个简化的接口。
    ```java class SubsystemA { public void operationA() { System.out.println("子系统A的操作"); } }

    class SubsystemB { public void operationB() { System.out.println("子系统B的操作"); } }

    class Facade { private SubsystemA subsystemA; private SubsystemB subsystemB;

    public Facade() {
        subsystemA = new SubsystemA();
        subsystemB = new SubsystemB();
    }
    
    public void operation() {
        subsystemA.operationA();
        subsystemB.operationB();
    }
    

    } ```

  2. 享元模式(Flyweight Pattern)
    享元模式通过共享对象来有效地支持大量细粒度的对象。
    ```java class Flyweight { private String intrinsicState;

    public Flyweight(String intrinsicState) {
        this.intrinsicState = intrinsicState;
    }
    
    public void operation(String extrinsicState) {
        System.out.println("内部状态: " + intrinsicState + ", 外部状态: " + extrinsicState);
    }
    

    }

    class FlyweightFactory { private Map flyweights = new HashMap<>();

    public Flyweight getFlyweight(String key) {
        if (!flyweights.containsKey(key)) {
            flyweights.put(key, new Flyweight(key));
        }
        return flyweights.get(key);
    }
    

    } ```

  3. 代理模式(Proxy Pattern)
    代理模式为其他对象提供一种代理以控制对这个对象的访问。
    ```java interface Subject { void request(); }

    class RealSubject implements Subject { public void request() { System.out.println("真实主题的请求"); } }

    class Proxy implements Subject { private RealSubject realSubject;

    public void request() {
        if (realSubject == null) {
            realSubject = new RealSubject();
        }
        realSubject.request();
    }
    

    } ```

行为型模式

  1. 责任链模式(Chain of Responsibility Pattern)
    责任链模式将请求的发送者和接收者解耦,形成一个处理请求的链。
    ```java abstract class Handler { protected Handler next;

    public void setNext(Handler next) {
        this.next = next;
    }
    
    public abstract void handleRequest(int request);
    

    }

    class ConcreteHandlerA extends Handler { public void handleRequest(int request) { if (request < 10) { System.out.println("处理请求A: " + request); } else if (next != null) { next.handleRequest(request); } } } ```

  2. 命令模式(Command Pattern)
    命令模式将请求封装为对象,使你可以用不同的请求对客户进行参数化。
    ```java interface Command { void execute(); }

    class ConcreteCommand implements Command { private Receiver receiver;

    public ConcreteCommand(Receiver receiver) {
        this.receiver = receiver;
    }
    
    public void execute() {
        receiver.action();
    }
    

    }

    class Receiver { public void action() { System.out.println("执行请求"); } }

    class Invoker { private Command command;

    public void setCommand(Command command) {
        this.command = command;
    }
    
    public void executeCommand() {
        command.execute();
    }
    

    } ```

  3. 解释器模式(Interpreter Pattern)
    解释器模式用于给定一门语言,定义一个表示该语言句子的文法,并提供一个解释程序。
    ```java interface Expression { int interpret(); }

    class NumberExpression implements Expression { private int number;

    public NumberExpression(int number) {
        this.number = number;
    }
    
    public int interpret() {
        return number;
    }
    

    }

    class AddExpression implements Expression { private Expression left; private Expression right;

    public AddExpression(Expression left, Expression right) {
        this.left = left;
        this.right = right;
    }
    
    public int interpret() {
        return left.interpret() + right.interpret();
    }
    

    } ```

  4. 迭代器模式(Iterator Pattern)
    迭代器模式提供一种顺序访问集合对象的方法,而不暴露其内部表示。
    ```java interface Iterator { boolean hasNext(); Object next(); }

    interface Aggregate { Iterator createIterator(); }

    class ConcreteAggregate implements Aggregate { private List items = new ArrayList<>();

    public void add(Object item) {
        items.add(item);
    }
    
    public Iterator createIterator() {
        return new ConcreteIterator(this);
    }
    
    public List<Object> getItems() {
        return items;
    }
    

    }

    class ConcreteIterator implements Iterator { private ConcreteAggregate aggregate; private int current = 0;

    public ConcreteIterator(ConcreteAggregate aggregate) {
        this.aggregate = aggregate;
    }
    
    public boolean hasNext() {
        return current < aggregate.getItems().size();
    }
    
    public Object next() {
        return aggregate.getItems().get(current++);
    }
    

    } ```

  5. 观察者模式(Observer Pattern)
    观察者模式定义了一种一对多的依赖关系,使得每当一个对象的状态发生改变时,其依赖者都会得到通知并自动更新。
    ```java interface Observer { void update(String message); }

    class ConcreteObserver implements Observer { private String name;

    public ConcreteObserver(String name) {
        this.name = name;
    }
    
    public void update(String message) {
        System.out.println(name + " 收到消息: " + message);
    }
    

    }

    class Subject { private List observers = new ArrayList<>();

    public void attach(Observer observer) {
        observers.add(observer);
    }
    
    public void notifyObservers(String message) {
        for (Observer observer : observers) {
            observer.update(message);
        }
    }
    

    } ```

  6. 状态模式(State Pattern)
    状态模式允许对象在内部状态改变时改变它的行为。
    ```java interface State { void handle(Context context); }

    class ConcreteStateA implements State { public void handle(Context context) { System.out.println("处理状态A"); context.setState(new ConcreteStateB()); } }

    class ConcreteStateB implements State { public void handle(Context context) { System.out.println("处理状态B"); context.setState(new ConcreteStateA()); } }

    class Context { private State state;

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

    } ```

  7. 策略模式(Strategy Pattern)
    策略模式定义了一系列算法,将每一个算法封装起来,并使它们可以互换。
    ```java interface Strategy { void execute(); }

    class ConcreteStrategyA implements Strategy { public void execute() { System.out.println("执行策略A"); } }

    class ConcreteStrategyB implements Strategy { public void execute() { System.out.println("执行策略B"); } }

    class Context { private Strategy strategy;

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

    } ```

  8. 模板方法模式(Template Method Pattern)
    模板方法模式定义一个操作的骨架,在子类中实现某些步骤。
    ```java abstract class AbstractClass { public final void templateMethod() { step1(); step2(); hook(); }

    abstract void step1();
    abstract void step2();
    
    void hook() {}
    

    }

    class ConcreteClass extends AbstractClass { void step1() { System.out.println("具体步骤1"); }

    void step2() {
        System.out.println("具体步骤2");
    }
    

    } ```

  9. 访问者模式(Visitor Pattern)
    访问者模式表示一个作用于某对象结构中的各元素的操作。
    ```java interface Visitor { void visit(ConcreteElementA element); void visit(ConcreteElementB element); }

    interface Element { void accept(Visitor visitor); }

    class ConcreteElementA implements Element { public void accept(Visitor visitor) { visitor.visit(this); } }

    class ConcreteElementB implements Element { public void accept(Visitor visitor) { visitor.visit(this); } }

    class ConcreteVisitor implements Visitor { public void visit(ConcreteElementA element) { System.out.println("访问A"); }

    public void visit(ConcreteElementB element) {
        System.out.println("访问B");
    }
    

    } ```

  10. 中介者模式(Mediator Pattern)
    中介者模式定义一个对象,封装一系列的对象交互。
    ```java class Mediator { private ColleagueA colleagueA; private ColleagueB colleagueB;

    public void setColleagueA(ColleagueA colleagueA) {
        this.colleagueA = colleagueA;
    }
    
    public void setColleagueB(ColleagueB colleagueB) {
        this.colleagueB = colleagueB;
    }
    
    public void mediate() {
        // 中介逻辑
    }
    

    } ```

  11. 备忘录模式(Memento Pattern)
    备忘录模式允许在不暴露对象实现细节的情况下保存和恢复对象的状态。
    ```java class Memento { private String state;

    public Memento(String state) {
        this.state = state;
    }
    
    public String getState() {
        return state;
    }
    

    }

    class Originator { private String state;

    public void setState(String state) {
        this.state = state;
    }
    
    public Memento saveStateToMemento() {
        return new Memento(state);
    }
    
    public void getStateFromMemento(Memento memento) {
        state = memento.getState();
    }
    

    } ```

  12. 以上便是Java中23种设计模式的简单介绍和代码示例。设计模式为程序员提供了一系列有效的解决方案,以提高代码的灵活性和可维护性。理解和应用这些设计模式将对编写高质量的Java代码大有裨益。

    点赞(0) 打赏