Java 23种设计模式详细教程

设计模式是软件设计中常见问题的典型解决方案,它们代表了最佳实践,是众多软件开发人员经过长期试验和错误总结出来的。Java设计模式通常分为三大类:创建型模式、结构型模式和行为型模式。

一、创建型模式(5种)

1. 单例模式 (Singleton)

目的:确保一个类只有一个实例,并提供全局访问点。

public class Singleton {
    private static Singleton instance;

    private Singleton() {}

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

变体

  • 饿汉式:类加载时就初始化
  • 懒汉式:第一次使用时初始化
  • 双重检查锁:线程安全
  • 静态内部类:延迟加载且线程安全
  • 枚举实现:防止反射攻击

2. 工厂方法模式 (Factory Method)

目的:定义一个创建对象的接口,但让子类决定实例化哪个类。

interface Product {
    void use();
}
class ConcreteProduct implements Product {
    public void use() {
        System.out.println("Using ConcreteProduct");
    }
}
abstract class Creator {
    public abstract Product factoryMethod();
}
class ConcreteCreator extends Creator {
    public Product factoryMethod() {
        return new ConcreteProduct();
    }
}

3. 抽象工厂模式 (Abstract Factory)

目的:提供一个接口,用于创建相关或依赖对象的家族,而不需要明确指定具体类。

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

4. 建造者模式 (Builder)

目的:将一个复杂对象的构建与其表示分离,使得同样的构建过程可以创建不同的表示。

class Product {
    private String part1;
    private String part2;
    // setters and getters
}
interface Builder {
    void buildPart1(String part1);
    void buildPart2(String part2);
    Product getResult();
}
class ConcreteBuilder implements Builder {
    private Product product = new Product();

    public void buildPart1(String part1) {
        product.setPart1(part1);
    }

    public void buildPart2(String part2) {
        product.setPart2(part2);
    }

    public Product getResult() {
        return product;
    }
}
class Director {
    public Product construct(Builder builder) {
        builder.buildPart1("part1");
        builder.buildPart2("part2");
        return builder.getResult();
    }
}

5. 原型模式 (Prototype)

目的:通过复制现有的实例来创建新的实例。

interface Prototype extends Cloneable {
    Prototype clone() throws CloneNotSupportedException;
}
class ConcretePrototype implements Prototype {
    public Prototype clone() throws CloneNotSupportedException {
        return (Prototype)super.clone();
    }
}

二、结构型模式(7种)

6. 适配器模式 (Adapter)

目的:将一个类的接口转换成客户希望的另一个接口。

interface Target {
    void request();
}
class Adaptee {
    public void specificRequest() {
        System.out.println("Specific request");
    }
}
class Adapter implements Target {
    private Adaptee adaptee;

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

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

7. 桥接模式 (Bridge)

目的:将抽象部分与实现部分分离,使它们都可以独立变化。

interface Implementor {
    void operationImpl();
}
class ConcreteImplementorA implements Implementor {
    public void operationImpl() {
        System.out.println("ConcreteImplementorA");
    }
}
abstract class Abstraction {
    protected Implementor implementor;

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

    public abstract void operation();
}
class RefinedAbstraction extends Abstraction {
    public RefinedAbstraction(Implementor implementor) {
        super(implementor);
    }

    public void operation() {
        implementor.operationImpl();
    }
}

8. 组合模式 (Composite)

目的:将对象组合成树形结构以表示"部分-整体"的层次结构。

interface Component {
    void operation();
}
class Leaf implements Component {
    public void operation() {
        System.out.println("Leaf operation");
    }
}
class Composite implements Component {
    private List<Component> children = new ArrayList<>();

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

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

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

9. 装饰器模式 (Decorator)

目的:动态地给一个对象添加一些额外的职责。

interface Component {
    void operation();
}
class ConcreteComponent implements Component {
    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 ConcreteDecoratorA extends Decorator {
    public ConcreteDecoratorA(Component component) {
        super(component);
    }

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

    private void addedBehavior() {
        System.out.println("Added behavior from ConcreteDecoratorA");
    }
}

10. 外观模式 (Facade)

目的:为子系统中的一组接口提供一个一致的界面。

class SubsystemA {
    public void operationA() {
        System.out.println("SubsystemA operation");
    }
}
class SubsystemB {
    public void operationB() {
        System.out.println("SubsystemB operation");
    }
}
class Facade {
    private SubsystemA subsystemA = new SubsystemA();
    private SubsystemB subsystemB = new SubsystemB();

    public void operation() {
        subsystemA.operationA();
        subsystemB.operationB();
    }
}

11. 享元模式 (Flyweight)

目的:运用共享技术有效地支持大量细粒度的对象。

class Flyweight {
    private String intrinsicState;

    public Flyweight(String intrinsicState) {
        this.intrinsicState = intrinsicState;
    }

    public void operation(String extrinsicState) {
        System.out.println("Intrinsic: " + intrinsicState + ", Extrinsic: " + extrinsicState);
    }
}
class FlyweightFactory {
    private Map<String, Flyweight> flyweights = new HashMap<>();

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

12. 代理模式 (Proxy)

目的:为其他对象提供一种代理以控制对这个对象的访问。

interface Subject {
    void request();
}
class RealSubject implements Subject {
    public void request() {
        System.out.println("RealSubject request");
    }
}
class Proxy implements Subject {
    private RealSubject realSubject;

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

    private void preRequest() {
        System.out.println("Pre request");
    }

    private void postRequest() {
        System.out.println("Post request");
    }
}

三、行为型模式(11种)

13. 责任链模式 (Chain of Responsibility)

目的:使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。

abstract class Handler {
    protected Handler successor;

    public void setSuccessor(Handler successor) {
        this.successor = successor;
    }

    public abstract void handleRequest(Request request);
}
class ConcreteHandlerA extends Handler {
    public void handleRequest(Request request) {
        if (canHandle(request)) {
            // 处理请求
        } else if (successor != null) {
            successor.handleRequest(request);
        }
    }

    private boolean canHandle(Request request) {
        // 判断是否能处理
        return true;
    }
}

14. 命令模式 (Command)

目的:将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化。

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("Receiver action");
    }
}
class Invoker {
    private Command command;

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

    public void executeCommand() {
        command.execute();
    }
}

15. 解释器模式 (Interpreter)

目的:给定一个语言,定义它的文法的一种表示,并定义一个解释器。

interface Expression {
    boolean interpret(String context);
}
class TerminalExpression implements Expression {
    private String data;

    public TerminalExpression(String data) {
        this.data = data;
    }

    public boolean interpret(String context) {
        return context.contains(data);
    }
}
class OrExpression implements Expression {
    private Expression expr1;
    private Expression expr2;

    public OrExpression(Expression expr1, Expression expr2) {
        this.expr1 = expr1;
        this.expr2 = expr2;
    }

    public boolean interpret(String context) {
        return expr1.interpret(context) || expr2.interpret(context);
    }
}

16. 迭代器模式 (Iterator)

目的:提供一种方法顺序访问一个聚合对象中的各个元素,而又不暴露其内部的表示。

interface Iterator<T> {
    boolean hasNext();
    T next();
}
interface Aggregate<T> {
    Iterator<T> createIterator();
}
class ConcreteAggregate<T> implements Aggregate<T> {
    private List<T> items = new ArrayList<>();

    public Iterator<T> createIterator() {
        return new ConcreteIterator<T>(this);
    }

    public int size() {
        return items.size();
    }

    public T get(int index) {
        return items.get(index);
    }
}
class ConcreteIterator<T> implements Iterator<T> {
    private ConcreteAggregate<T> aggregate;
    private int index = 0;

    public ConcreteIterator(ConcreteAggregate<T> aggregate) {
        this.aggregate = aggregate;
    }

    public boolean hasNext() {
        return index < aggregate.size();
    }

    public T next() {
        return aggregate.get(index++);
    }
}

17. 中介者模式 (Mediator)

目的:用一个中介对象来封装一系列的对象交互。

interface Mediator {
    void notify(Colleague sender, String event);
}
class ConcreteMediator implements Mediator {
    private Colleague colleague1;
    private Colleague colleague2;

    public void setColleague1(Colleague colleague1) {
        this.colleague1 = colleague1;
    }

    public void setColleague2(Colleague colleague2) {
        this.colleague2 = colleague2;
    }

    public void notify(Colleague sender, String event) {
        if (sender == colleague1) {
            colleague2.receive(event);
        } else {
            colleague1.receive(event);
        }
    }
}
abstract class Colleague {
    protected Mediator mediator;

    public Colleague(Mediator mediator) {
        this.mediator = mediator;
    }

    public abstract void send(String event);
    public abstract void receive(String event);
}
class ConcreteColleague1 extends Colleague {
    public ConcreteColleague1(Mediator mediator) {
        super(mediator);
    }

    public void send(String event) {
        mediator.notify(this, event);
    }

    public void receive(String event) {
        System.out.println("Colleague1 received: " + event);
    }
}

18. 备忘录模式 (Memento)

目的:在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。

class Originator {
    private String state;

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

    public String getState() {
        return state;
    }

    public Memento saveStateToMemento() {
        return new Memento(state);
    }

    public void getStateFromMemento(Memento memento) {
        state = memento.getState();
    }
}
class Memento {
    private String state;

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

    public String getState() {
        return state;
    }
}
class CareTaker {
    private List<Memento> mementoList = new ArrayList<>();

    public void add(Memento state) {
        mementoList.add(state);
    }

    public Memento get(int index) {
        return mementoList.get(index);
    }
}

19. 观察者模式 (Observer)

目的:定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。

interface Subject {
    void registerObserver(Observer o);
    void removeObserver(Observer o);
    void notifyObservers();
}
class ConcreteSubject implements Subject {
    private List<Observer> observers = new ArrayList<>();
    private int state;

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

    public void registerObserver(Observer o) {
        observers.add(o);
    }

    public void removeObserver(Observer o) {
        observers.remove(o);
    }

    public void notifyObservers() {
        for (Observer observer : observers) {
            observer.update(state);
        }
    }
}
interface Observer {
    void update(int state);
}
class ConcreteObserver implements Observer {
    public void update(int state) {
        System.out.println("Observer notified. New state: " + state);
    }
}

20. 状态模式 (State)

目的:允许一个对象在其内部状态改变时改变它的行为。

interface State {
    void handle(Context context);
}
class ConcreteStateA implements State {
    public void handle(Context context) {
        System.out.println("Handling in State A");
        context.setState(new ConcreteStateB());
    }
}
class ConcreteStateB implements State {
    public void handle(Context context) {
        System.out.println("Handling in State B");
        context.setState(new ConcreteStateA());
    }
}
class Context {
    private State state;

    public Context(State state) {
        this.state = state;
    }

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

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

21. 策略模式 (Strategy)

目的:定义一系列的算法,把它们一个个封装起来,并且使它们可相互替换。

interface Strategy {
    int doOperation(int num1, int num2);
}
class OperationAdd implements Strategy {
    public int doOperation(int num1, int num2) {
        return num1 + num2;
    }
}
class OperationSubtract implements Strategy {
    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);
    }
}

22. 模板方法模式 (Template Method)

目的:定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。

abstract class AbstractClass {
    public final void templateMethod() {
        primitiveOperation1();
        primitiveOperation2();
        concreteOperation();
    }

    protected abstract void primitiveOperation1();
    protected abstract void primitiveOperation2();

    private void concreteOperation() {
        System.out.println("Common operation");
    }
}
class ConcreteClass extends AbstractClass {
    protected void primitiveOperation1() {
        System.out.println("Concrete operation 1");
    }

    protected void primitiveOperation2() {
        System.out.println("Concrete operation 2");
    }
}

23. 访问者模式 (Visitor)

目的:表示一个作用于某对象结构中的各元素的操作。

interface Visitor {
    void visit(ElementA element);
    void visit(ElementB element);
}
class ConcreteVisitor implements Visitor {
    public void visit(ElementA element) {
        System.out.println("Visitor processing ElementA");
    }

    public void visit(ElementB element) {
        System.out.println("Visitor processing ElementB");
    }
}
interface Element {
    void accept(Visitor visitor);
}
class ElementA implements Element {
    public void accept(Visitor visitor) {
        visitor.visit(this);
    }
}
class ElementB implements Element {
    public void accept(Visitor visitor) {
        visitor.visit(this);
    }
}
class ObjectStructure {
    private List<Element> elements = new ArrayList<>();

    public void add(Element element) {
        elements.add(element);
    }

    public void accept(Visitor visitor) {
        for (Element element : elements) {
            element.accept(visitor);
        }
    }
}

四、设计模式的选择与应用

如何选择设计模式

  1. 理解问题:首先明确你要解决的问题是什么
  2. 模式目的:了解每个模式的意图和适用场景
  3. 权衡利弊:考虑模式的复杂性和带来的好处
  4. 重构现有代码:有时在重构时发现模式的应用点

设计模式的最佳实践

  1. 不要过度设计:只在必要时使用设计模式
  2. 组合使用:多个模式可以一起使用解决复杂问题
  3. 保持简单:优先选择简单的解决方案
  4. 理解原理:不要机械套用,理解背后的思想

常见设计模式组合

  • MVC架构:组合使用观察者、策略和组合模式
  • 复杂对象创建:工厂方法+建造者+原型
  • 复杂行为管理:状态+策略+责任链 设计模式是提高代码质量、可维护性和可扩展性的强大工具,但需要在实际开发中不断实践才能真正掌握。









results matching ""

    No results matching ""