23种经典设计模式(GoF设计模式)
目录
🍀 创建型设计模式(5种)
1. 单例模式(Singleton)
2. 工厂方法模式(Factory Method)
3. 抽象工厂模式(Abstract Factory)
4. 建造者模式(Builder)
5. 原型模式(Prototype)
🌉 结构型设计模式(7种)
6. 适配器模式(Adapter)
7. 桥接模式(Bridge)
8. 装饰器模式(Decorator)
9. 组合模式(Composite)
10. 外观模式(Facade)
11. 享元模式(Flyweight)
12. 代理模式(Proxy)
🔄 行为型设计模式(11种)
13. 责任链模式(Chain of Responsibility)
14. 命令模式(Command)
15. 解释器模式(Interpreter)
16. 迭代器模式(Iterator)
17. 中介者模式(Mediator)
18. 备忘录模式(Memento)
19. 观察者模式(Observer)
20. 状态模式(State)
21. 策略模式(Strategy)
22. 模板方法模式(Template Method)
23. 访问者模式(Visitor)
好的,下面是软件设计师应掌握的 23种经典设计模式(GoF设计模式),包括每个模式的简要说明、适用场景的生动描述、主要优点,并附上 Java 代码示例,方便理解和实战参考。
🍀 创建型设计模式(5种)
1. 单例模式(Singleton)
-
问题:如何确保一个类只有一个实例?
-
好处:节省资源,避免多次创建重复对象。
-
示例:
public class Singleton {private static Singleton instance = new Singleton();private Singleton() {}public static Singleton getInstance() {return instance;}
}
2. 工厂方法模式(Factory Method)
-
问题:对象创建代码混杂在业务中,难以扩展。
-
好处:创建对象的过程被抽象,便于扩展。
-
示例:
interface Product { void use(); }
class ConcreteProduct implements Product { public void use() { System.out.println("Use Product"); } }
class Factory {public Product createProduct() { return new ConcreteProduct(); }
}
3. 抽象工厂模式(Abstract Factory)
-
问题:如何创建一系列相关的对象而不依赖具体类?
-
好处:保证产品族的一致性。
-
示例:
interface Button { void paint(); }
interface Checkbox { void check(); }class WinButton implements Button { public void paint() { System.out.println("Win Button"); } }
class MacButton implements Button { public void paint() { System.out.println("Mac Button"); } }interface GUIFactory {Button createButton();Checkbox createCheckbox();
}class WinFactory implements GUIFactory {public Button createButton() { return new WinButton(); }public Checkbox createCheckbox() { return null; }
}
4. 建造者模式(Builder)
-
问题:构建一个复杂对象时构造过程难以管理。
-
好处:一步一步创建对象,清晰可控。
-
示例:
class Product {String partA, partB;
}
class Builder {private Product product = new Product();Builder buildPartA() { product.partA = "A"; return this; }Builder buildPartB() { product.partB = "B"; return this; }Product build() { return product; }
}
5. 原型模式(Prototype)
-
问题:对象创建成本太高。
-
好处:通过复制已有对象快速创建新对象。
-
示例:
class Prototype implements Cloneable {public Prototype clone() throws CloneNotSupportedException {return (Prototype) super.clone();}
}
🌉 结构型设计模式(7种)
6. 适配器模式(Adapter)
-
问题:两个不兼容的接口如何协同工作?
-
好处:让老代码焕发生机。
-
示例:
class Adaptee { void specificRequest() { System.out.println("Old Method"); } }
interface Target { void request(); }
class Adapter implements Target {Adaptee adaptee = new Adaptee();public void request() { adaptee.specificRequest(); }
}
7. 桥接模式(Bridge)
-
问题:类的维度太多,继承爆炸。
-
好处:分离抽象与实现,降低耦合。
-
示例:
interface Color { void fill(); }
class Red implements Color { public void fill() { System.out.println("Red"); } }abstract class Shape {protected Color color;Shape(Color color) { this.color = color; }abstract void draw();
}class Circle extends Shape {Circle(Color color) { super(color); }void draw() { color.fill(); System.out.println("Draw Circle"); }
}
8. 装饰器模式(Decorator)
-
问题:不能通过继承灵活添加新功能。
-
好处:在不修改原类的情况下添加功能。
-
示例:
interface Coffee { String getDescription(); }
class SimpleCoffee implements Coffee {public String getDescription() { return "Simple Coffee"; }
}
class MilkDecorator implements Coffee {private Coffee coffee;MilkDecorator(Coffee coffee) { this.coffee = coffee; }public String getDescription() { return coffee.getDescription() + ", Milk"; }
}
9. 组合模式(Composite)
-
问题:如何统一处理单个对象与对象组合?
-
好处:树形结构处理更优雅。
-
示例:
interface Component { void show(); }
class Leaf implements Component {public void show() { System.out.println("Leaf"); }
}
class Composite implements Component {private List<Component> children = new ArrayList<>();public void add(Component c) { children.add(c); }public void show() {for (Component c : children) c.show();}
}
10. 外观模式(Facade)
-
问题:系统太复杂,调用不方便。
-
好处:提供统一接口,简化调用。
-
示例:
class CPU { void start() { System.out.println("CPU Start"); } }
class Memory { void load() { System.out.println("Memory Load"); } }
class Computer {CPU cpu = new CPU(); Memory memory = new Memory();void start() {cpu.start(); memory.load();}
}
11. 享元模式(Flyweight)
-
问题:大量相似对象导致内存浪费。
-
好处:共享相同部分,节省资源。
-
示例:
class Flyweight {private String intrinsic;Flyweight(String intrinsic) { this.intrinsic = intrinsic; }void operate(String extrinsic) {System.out.println("Intrinsic: " + intrinsic + ", Extrinsic: " + extrinsic);}
}
class FlyweightFactory {private Map<String, Flyweight> pool = new HashMap<>();Flyweight get(String key) {return pool.computeIfAbsent(key, Flyweight::new);}
}
12. 代理模式(Proxy)
-
问题:如何控制对对象的访问?
-
好处:增强功能,如懒加载、安全检查。
-
示例:
interface Subject { void request(); }
class RealSubject implements Subject {public void request() { System.out.println("Real Request"); }
}
class ProxySubject implements Subject {private RealSubject real = new RealSubject();public void request() {System.out.println("Proxy log...");real.request();}
}
🔄 行为型设计模式(11种)
13. 责任链模式(Chain of Responsibility)
-
问题:请求者与处理者强耦合。
-
好处:动态传递请求,解耦处理逻辑。
-
示例:
abstract class Handler {protected Handler next;void setNext(Handler next) { this.next = next; }abstract void handle(String request);
}
class ConcreteHandler extends Handler {void handle(String request) {if ("task".equals(request)) System.out.println("Handled");else if (next != null) next.handle(request);}
}
14. 命令模式(Command)
-
问题:如何将请求封装为对象?
-
好处:支持撤销、日志等操作。
-
示例:
interface Command { void execute(); }
class Light {void on() { System.out.println("Light On"); }
}
class LightOnCommand implements Command {private Light light;LightOnCommand(Light light) { this.light = light; }public void execute() { light.on(); }
}
15. 解释器模式(Interpreter)
-
问题:如何解释某种语言的语法?
-
好处:自定义语言的核心。
-
示例:
interface Expression { int interpret(); }
class Number implements Expression {int value;Number(int value) { this.value = value; }public int interpret() { return value; }
}
16. 迭代器模式(Iterator)
-
问题:访问集合内部结构太复杂。
-
好处:统一遍历方式。
-
示例:
List<String> list = Arrays.asList("a", "b", "c");
Iterator<String> it = list.iterator();
while (it.hasNext()) {System.out.println(it.next());
}
17. 中介者模式(Mediator)
-
问题:对象之间关系复杂。
-
好处:集中控制对象交互。
-
示例:
interface Mediator { void notify(String event); }
class ConcreteMediator implements Mediator {public void notify(String event) {System.out.println("Mediator handles: " + event);}
}
18. 备忘录模式(Memento)
-
问题:如何保存对象的历史状态?
-
好处:支持撤销操作。
-
示例:
class Memento {String state;Memento(String state) { this.state = state; }
}
class Originator {String state;Memento save() { return new Memento(state); }void restore(Memento m) { this.state = m.state; }
}
19. 观察者模式(Observer)
-
问题:多个对象需要在状态变化时同步响应。
-
好处:实现发布-订阅机制。
-
示例:
interface Observer { void update(String msg); }
class Subject {List<Observer> observers = new ArrayList<>();void addObserver(Observer o) { observers.add(o); }void notifyAll(String msg) {for (Observer o : observers) o.update(msg);}
}
20. 状态模式(State)
-
问题:对象状态多,条件判断复杂。
-
好处:将状态逻辑分离,清晰可控。
-
示例:
interface State { void handle(); }
class OnState implements State {public void handle() { System.out.println("Light is ON"); }
}
class Light {private State state;void setState(State state) { this.state = state; }void press() { state.handle(); }
}
21. 策略模式(Strategy)
-
问题:算法多种多样,代码不好维护。
-
好处:将算法封装为独立策略,便于切换。
-
示例:
interface Strategy { int execute(int a, int b); }
class Add implements Strategy {public int execute(int a, int b) { return a + b; }
}
22. 模板方法模式(Template Method)
-
问题:多个类的结构相同,但实现不同。
-
好处:复用流程逻辑,子类自定义细节。
-
示例:
abstract class AbstractClass {void templateMethod() {step1(); step2();}abstract void step1();abstract void step2();
}
23. 访问者模式(Visitor)
-
问题:数据结构稳定但操作多变。
-
好处:将操作封装到访问者中。
-
示例:
interface Visitor { void visit(Element e); }
interface Element { void accept(Visitor v); }
class ConcreteElement implements Element {public void accept(Visitor v) { v.visit(this); }
}
如果你需要这些模式的完整源代码打包或想了解每个模式的应用场景案例(比如在Spring、JDK中的应用),我也可以为你整理。是否需要生成一个 Markdown 或 PDF 版文档?