Java设计模式概览

Java 设计模式

  • Java 设计模式详解
    • 一、设计模式概述
      • 1. 为什么需要设计模式
      • 2. 设计模式分类
    • 二、创建型模式 (5种)
      • 1. 单例模式 (Singleton)
      • 2. 工厂方法模式 (Factory Method)
      • 3. 抽象工厂模式 (Abstract Factory)
      • 4. 建造者模式 (Builder)
      • 5. 原型模式 (Prototype)
    • 三、结构型模式 (7种)
      • 1. 适配器模式 (Adapter)
      • 2. 桥接模式 (Bridge)
      • 3. 组合模式 (Composite)
      • 4. 装饰器模式 (Decorator)
      • 5. 外观模式 (Facade)
      • 6. 享元模式 (Flyweight)
      • 7. 代理模式 (Proxy)
    • 四、行为型模式 (11种)
      • 1. 责任链模式 (Chain of Responsibility)
      • 2. 命令模式 (Command)
      • 3. 解释器模式 (Interpreter)
      • 4. 迭代器模式 (Iterator)
      • 5. 中介者模式 (Mediator)
      • 6. 备忘录模式 (Memento)
      • 7. 观察者模式 (Observer)
      • 8. 状态模式 (State)
      • 9. 策略模式 (Strategy)
      • 10. 模板方法模式 (Template Method)
      • 11. 访问者模式 (Visitor)
    • 五、设计模式的基本原则
      • 1. SOLID 原则
      • 2. DRY 原则
      • 3. KISS 原则
      • 4. YAGNI 原则
      • 5. LoD(迪米特法则)
    • 六、设计模式的关系与对比
      • 1. 相似模式对比
      • 2. 模式组合应用
    • 七、设计模式在现代框架中的应用
      • 1. Spring 框架中的模式
      • 2. Java EE 中的模式
    • 八、设计模式的反模式
      • 1. 常见反模式
      • 2. 过度使用模式的危害
    • 九、设计模式的选择与使用原则
      • 1. 如何选择设计模式
      • 2. 设计模式的最佳实践
      • 3. 常见误区
    • 十、总结

Java 设计模式详解

一、设计模式概述

1. 为什么需要设计模式

  • 提供通用的解决方案,避免重复造轮子
  • 提高代码的可重用性和可维护性
  • 促进团队间的沟通(使用模式名称即可表达复杂思想)
  • 帮助开发者编写更灵活、可扩展的代码

2. 设计模式分类

  • 创建型模式:处理对象创建机制
  • 结构型模式:处理类和对象的组合
  • 行为型模式:处理对象间的通信

二、创建型模式 (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)

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

public interface Product {
    void use();
}

public class ConcreteProduct implements Product {
    public void use() {
        System.out.println("Using ConcreteProduct");
    }
}

public abstract class Creator {
    public abstract Product factoryMethod();
}

public class ConcreteCreator extends Creator {
    public Product factoryMethod() {
        return new ConcreteProduct();
    }
}

应用场景

  • JDBC 的 Connection 对象创建
  • 日志框架中的 Appender 创建

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

目的:提供一个接口,用于创建相关或依赖对象的家族

public interface AbstractFactory {
    ProductA createProductA();
    ProductB createProductB();
}

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

public class ConcreteFactory2 implements AbstractFactory {
    public ProductA createProductA() { 
        return new ProductA2(); 
    }
    public ProductB createProductB() { 
        return new ProductB2(); 
    }
}

应用场景

  • GUI 工具包
  • 数据库访问层

4. 建造者模式 (Builder)

目的:将一个复杂对象的构建与其表示分离

public class Computer {
    private String CPU;
    private String RAM;
    
    public static class Builder {
        private String CPU;
        private String RAM;
        
        public Builder setCPU(String CPU) {
            this.CPU = CPU;
            return this;
        }
        
        public Builder setRAM(String RAM) {
            this.RAM = RAM;
            return this;
        }
        
        public Computer build() {
            Computer computer = new Computer();
            computer.CPU = this.CPU;
            computer.RAM = this.RAM;
            return computer;
        }
    }
}

应用场景

  • 创建复杂对象
  • 多个构造参数且可选时

5. 原型模式 (Prototype)

目的:通过复制现有对象来创建新对象

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

public class ConcretePrototype extends Prototype {
    private String field;
    
    public ConcretePrototype(String field) {
        this.field = field;
    }
    
    public void setField(String field) {
        this.field = field;
    }
    
    public String getField() {
        return field;
    }
}

应用场景

  • 创建对象成本较高时
  • 需要保存对象状态

三、结构型模式 (7种)

1. 适配器模式 (Adapter)

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

public interface Target {
    void request();
}

public class Adaptee {
    public void specificRequest() {
        System.out.println("Specific request");
    }
}

public class Adapter implements Target {
    private Adaptee adaptee;
    
    public Adapter(Adaptee adaptee) {
        this.adaptee = adaptee;
    }
    
    public void request() {
        adaptee.specificRequest();
    }
}

应用场景

  • 使用第三方库时接口不匹配
  • 旧系统改造

2. 桥接模式 (Bridge)

目的:将抽象部分与实现部分分离

public interface Implementor {
    void operationImpl();
}

public class ConcreteImplementorA implements Implementor {
    public void operationImpl() {
        System.out.println("Implementation A");
    }
}

public abstract class Abstraction {
    protected Implementor implementor;
    
    public Abstraction(Implementor implementor) {
        this.implementor = implementor;
    }
    
    public abstract void operation();
}

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

应用场景

  • GUI 开发
  • 驱动程序

3. 组合模式 (Composite)

目的:表示"部分-整体"的层次结构

public interface Component {
    void operation();
    void add(Component c);
    void remove(Component c);
    Component getChild(int i);
}

public class Leaf implements Component {
    public void operation() {
        System.out.println("Leaf operation");
    }
    
    public void add(Component c) {
        throw new UnsupportedOperationException();
    }
    
    public void remove(Component c) {
        throw new UnsupportedOperationException();
    }
    
    public Component getChild(int i) {
        throw new UnsupportedOperationException();
    }
}

public class Composite implements Component {
    private List children = new ArrayList<>();
    
    public void operation() {
        for (Component child : children) {
            child.operation();
        }
    }
    
    public void add(Component c) {
        children.add(c);
    }
    
    public void remove(Component c) {
        children.remove(c);
    }
    
    public Component getChild(int i) {
        return children.get(i);
    }
}

应用场景

  • 文件系统
  • GUI 组件树

4. 装饰器模式 (Decorator)

目的:动态添加职责

public interface Component {
    void operation();
}

public class ConcreteComponent implements Component {
    public void operation() {
        System.out.println("Basic operation");
    }
}

public abstract class Decorator implements Component {
    protected Component component;
    
    public Decorator(Component component) {
        this.component = component;
    }
    
    public void operation() {
        component.operation();
    }
}

public class ConcreteDecoratorA extends Decorator {
    public ConcreteDecoratorA(Component component) {
        super(component);
    }
    
    public void operation() {
        super.operation();
        addedBehavior();
    }
    
    private void addedBehavior() {
        System.out.println("Added behavior A");
    }
}

应用场景

  • Java I/O 流
  • 动态添加功能

5. 外观模式 (Facade)

目的:为子系统提供统一接口

public class SubsystemA {
    public void operationA() {
        System.out.println("Subsystem A operation");
    }
}

public class SubsystemB {
    public void operationB() {
        System.out.println("Subsystem B operation");
    }
}

public class Facade {
    private SubsystemA a;
    private SubsystemB b;
    
    public Facade() {
        a = new SubsystemA();
        b = new SubsystemB();
    }
    
    public void operation() {
        a.operationA();
        b.operationB();
    }
}

应用场景

  • 简化复杂系统
  • 分层设计

6. 享元模式 (Flyweight)

目的:支持大量细粒度对象

public interface Flyweight {
    void operation(String extrinsicState);
}

public class ConcreteFlyweight implements Flyweight {
    private String intrinsicState;
    
    public ConcreteFlyweight(String intrinsicState) {
        this.intrinsicState = intrinsicState;
    }
    
    public void operation(String extrinsicState) {
        System.out.println("Intrinsic: " + intrinsicState + 
                         ", Extrinsic: " + extrinsicState);
    }
}

public class FlyweightFactory {
    private Map pool = new HashMap<>();
    
    public Flyweight getFlyweight(String key) {
        if (!pool.containsKey(key)) {
            pool.put(key, new ConcreteFlyweight(key));
        }
        return pool.get(key);
    }
}

应用场景

  • 文本编辑器
  • 游戏对象

7. 代理模式 (Proxy)

目的:控制对象访问

public interface Subject {
    void request();
}

public class RealSubject implements Subject {
    public void request() {
        System.out.println("Real subject request");
    }
}

public 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");
    }
}

代理类型

  • 远程代理
  • 虚拟代理
  • 保护代理

应用场景

  • Spring AOP
  • Hibernate 延迟加载

四、行为型模式 (11种)

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

目的:使多个对象都有机会处理请求

public abstract class Handler {
    protected Handler successor;
    
    public void setSuccessor(Handler successor) {
        this.successor = successor;
    }
    
    public abstract void handleRequest(Request request);
}

public class ConcreteHandlerA extends Handler {
    public void handleRequest(Request request) {
        if (canHandle(request)) {
            System.out.println("Handled by A");
        } else if (successor != null) {
            successor.handleRequest(request);
        }
    }
    
    private boolean canHandle(Request request) {
        return request.getType().equals("A");
    }
}

应用场景

  • 异常处理
  • 审批流程

2. 命令模式 (Command)

目的:将请求封装为对象

public interface Command {
    void execute();
}

public class ConcreteCommand implements Command {
    private Receiver receiver;
    
    public ConcreteCommand(Receiver receiver) {
        this.receiver = receiver;
    }
    
    public void execute() {
        receiver.action();
    }
}

public class Receiver {
    public void action() {
        System.out.println("Receiver action");
    }
}

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

应用场景

  • 事务系统
  • 撤销功能

3. 解释器模式 (Interpreter)

目的:定义语言的文法表示

public interface Expression {
    boolean interpret(String context);
}

public class TerminalExpression implements Expression {
    private String data;
    
    public TerminalExpression(String data) {
        this.data = data;
    }
    
    public boolean interpret(String context) {
        return context.contains(data);
    }
}

public 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);
    }
}

应用场景

  • 正则表达式
  • SQL 解析

4. 迭代器模式 (Iterator)

目的:顺序访问聚合对象元素

public interface Iterator {
    boolean hasNext();
    T next();
}

public interface Aggregate {
    Iterator createIterator();
}

public class ConcreteAggregate implements Aggregate {
    private List items = new ArrayList<>();
    
    public Iterator createIterator() {
        return new ConcreteIterator(this);
    }
    
    public int size() {
        return items.size();
    }
    
    public T get(int index) {
        return items.get(index);
    }
    
    public void add(T item) {
        items.add(item);
    }
}

public class ConcreteIterator implements Iterator {
    private ConcreteAggregate aggregate;
    private int index = 0;
    
    public ConcreteIterator(ConcreteAggregate aggregate) {
        this.aggregate = aggregate;
    }
    
    public boolean hasNext() {
        return index < aggregate.size();
    }
    
    public T next() {
        if (hasNext()) {
            return aggregate.get(index++);
        }
        throw new NoSuchElementException();
    }
}

应用场景

  • 集合框架
  • 树形遍历

5. 中介者模式 (Mediator)

目的:封装对象交互

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

public class ConcreteColleagueA extends Colleague {
    public ConcreteColleagueA(Mediator mediator) {
        super(mediator);
    }
    
    public void send(String message) {
        mediator.send(message, this);
    }
    
    public void receive(String message) {
        System.out.println("ColleagueA received: " + message);
    }
}

public interface Mediator {
    void send(String message, Colleague colleague);
}

public class ConcreteMediator implements Mediator {
    private ConcreteColleagueA colleagueA;
    private ConcreteColleagueB colleagueB;
    
    public void setColleagueA(ConcreteColleagueA colleagueA) {
        this.colleagueA = colleagueA;
    }
    
    public void setColleagueB(ConcreteColleagueB colleagueB) {
        this.colleagueB = colleagueB;
    }
    
    public void send(String message, Colleague colleague) {
        if (colleague == colleagueA) {
            colleagueB.receive(message);
        } else {
            colleagueA.receive(message);
        }
    }
}

应用场景

  • GUI 通信
  • 聊天室

6. 备忘录模式 (Memento)

目的:捕获对象状态

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

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

public class CareTaker {
    private List mementoList = new ArrayList<>();
    
    public void add(Memento state) {
        mementoList.add(state);
    }
    
    public Memento get(int index) {
        return mementoList.get(index);
    }
}

应用场景

  • 撤销功能
  • 游戏存档

7. 观察者模式 (Observer)

目的:一对多依赖关系

public interface Subject {
    void registerObserver(Observer o);
    void removeObserver(Observer o);
    void notifyObservers();
}

public class ConcreteSubject implements Subject {
    private List observers = new ArrayList<>();
    private int state;
    
    public int getState() {
        return 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();
        }
    }
}

public interface Observer {
    void update();
}

public class ConcreteObserver implements Observer {
    private ConcreteSubject subject;
    
    public ConcreteObserver(ConcreteSubject subject) {
        this.subject = subject;
        subject.registerObserver(this);
    }
    
    public void update() {
        System.out.println("State changed to: " + subject.getState());
    }
}

应用场景

  • 事件处理
  • MVC

8. 状态模式 (State)

目的:根据状态改变行为

public interface State {
    void handle(Context context);
}

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

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

public 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);
    }
}

应用场景

  • 工作流引擎
  • 订单状态

9. 策略模式 (Strategy)

目的:封装可替换算法

public interface Strategy {
    int doOperation(int num1, int num2);
}

public class OperationAdd implements Strategy {
    public int doOperation(int num1, int num2) {
        return num1 + num2;
    }
}

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

public class Context {
    private Strategy strategy;
    
    public Context(Strategy strategy) {
        this.strategy = strategy;
    }
    
    public int executeStrategy(int num1, int num2) {
        return strategy.doOperation(num1, num2);
    }
}

应用场景

  • 支付方式
  • 排序算法

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

目的:定义算法骨架

public abstract class Game {
    abstract void initialize();
    abstract void startPlay();
    abstract void endPlay();
    
    public final void play() {
        initialize();
        startPlay();
        endPlay();
    }
}

public class Cricket extends Game {
    void initialize() {
        System.out.println("Cricket Game Initialized");
    }
    
    void startPlay() {
        System.out.println("Cricket Game Started");
    }
    
    void endPlay() {
        System.out.println("Cricket Game Finished");
    }
}

public class Football extends Game {
    void initialize() {
        System.out.println("Football Game Initialized");
    }
    
    void startPlay() {
        System.out.println("Football Game Started");
    }
    
    void endPlay() {
        System.out.println("Football Game Finished");
    }
}

应用场景

  • 框架设计
  • JUnit

11. 访问者模式 (Visitor)

目的:不改变元素类的前提下定义新操作

public interface ComputerPart {
    void accept(ComputerPartVisitor visitor);
}

public class Keyboard implements ComputerPart {
    public void accept(ComputerPartVisitor visitor) {
        visitor.visit(this);
    }
}

public interface ComputerPartVisitor {
    void visit(Computer computer);
    void visit(Mouse mouse);
    void visit(Keyboard keyboard);
    void visit(Monitor monitor);
}

public class ComputerPartDisplayVisitor implements ComputerPartVisitor {
    public void visit(Computer computer) {
        System.out.println("Displaying Computer");
    }
    
    public void visit(Mouse mouse) {
        System.out.println("Displaying Mouse");
    }
    
    public void visit(Keyboard keyboard) {
        System.out.println("Displaying Keyboard");
    }
    
    public void visit(Monitor monitor) {
        System.out.println("Displaying Monitor");
    }
}

应用场景

  • 编译器分析
  • XML处理

五、设计模式的基本原则

1. SOLID 原则

SOLID 是面向对象设计的五个基本原则:

  1. 单一职责原则 (SRP)

    • 一个类应该只有一个引起变化的原因
    • 示例:将数据持久化和业务逻辑分离到不同类
  2. 开闭原则 (OCP)

    • 软件实体应对扩展开放,对修改关闭
    • 示例:使用策略模式实现不同的算法扩展
  3. 里氏替换原则 (LSP)

    • 子类必须能够替换它们的基类
    • 示例:正方形不应继承长方形(因为修改边长行为不同)
  4. 接口隔离原则 (ISP)

    • 客户端不应被迫依赖它们不使用的接口
    • 示例:将大型接口拆分为多个专用接口
  5. 依赖倒置原则 (DIP)

    • 高层模块不应依赖低层模块,二者都应依赖抽象
    • 示例:通过依赖注入实现松耦合

2. DRY 原则

  • Don’t Repeat Yourself(不要重复自己)
  • 通过抽象消除重复代码
  • 示例:将通用功能提取到基类或工具类中

3. KISS 原则

  • Keep It Simple, Stupid(保持简单)
  • 避免不必要的复杂性
  • 示例:优先使用简单if-else而非策略模式(当逻辑简单时)

4. YAGNI 原则

  • You Aren’t Gonna Need It(你不会需要它)
  • 不要实现当前不需要的功能
  • 示例:避免过早优化或过度设计

5. LoD(迪米特法则)

  • 最少知识原则
  • 一个对象应当对其他对象有尽可能少的了解
  • 示例:通过外观模式封装子系统交互

六、设计模式的关系与对比

1. 相似模式对比

模式对比 关键区别
策略模式 vs 状态模式 策略是主动选择,状态是自动转换
装饰器模式 vs 代理模式 装饰器增强功能,代理控制访问
命令模式 vs 策略模式 命令封装动作和参数,策略封装算法

2. 模式组合应用

  • 工厂方法 + 原型模式:通过克隆创建对象
  • 组合模式 + 访问者模式:遍历复杂结构并执行操作
  • 观察者模式 + 中介者模式:协调多个对象间的通信

七、设计模式在现代框架中的应用

1. Spring 框架中的模式

  • 依赖注入:组合了工厂模式和策略模式
  • AOP:代理模式的典型实现
  • Bean作用域:单例和原型模式的应用

2. Java EE 中的模式

  • Servlet Filter:责任链模式
  • JMS:观察者模式的实现
  • EJB:外观模式和代理模式的结合

八、设计模式的反模式

1. 常见反模式

  • 上帝对象:违反单一职责原则
  • 贫血模型:将行为和数据分离的错误实践
  • 循环依赖:破坏模块化设计

2. 过度使用模式的危害

  • 可读性下降:简单问题复杂化
  • 维护成本增加:不必要的抽象层
  • 性能损耗:过多的间接调用

九、设计模式的选择与使用原则

1. 如何选择设计模式

  1. 明确问题:首先清楚你要解决什么问题
  2. 分析模式:了解各种模式的意图和适用场景
  3. 评估方案:考虑模式带来的复杂性和收益
  4. 保持简单:不要为了使用模式而使用模式

2. 设计模式的最佳实践

  • 理解原则而非死记硬背:理解SOLID原则比记住23种模式更重要
  • 适度使用:过度设计比设计不足更糟糕
  • 结合具体场景:没有放之四海皆准的模式
  • 重构到模式:先写出可工作的代码,再通过重构引入模式

3. 常见误区

  • 认为设计模式是银弹,能解决所有问题
  • 在不必要时使用复杂模式
  • 生搬硬套,不考虑实际场景
  • 忽视模式带来的复杂性

十、总结

Java设计模式是面向对象设计经验的总结,合理使用可以提高代码的:

  • 可维护性
  • 可扩展性
  • 重用性

关键原则:

  • 理解设计原则和适用场景 > 死记硬背实现代码
  • 根据具体问题选择合适模式
  • 避免过度设计

你可能感兴趣的:(设计模式,java,设计模式,开发语言)