设计模式全解析:23种经典设计模式及其应用
创建型模式
1. 单例模式(Singleton Pattern)
- 核心思想:确保一个类只有一个实例,并提供一个全局访问点。
- 适用场景:需要共享资源的场景,如配置管理、日志记录等。
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)
- 核心思想:定义一个创建对象的接口,但由子类决定实例化哪一个类。
- 适用场景:需要延迟到子类进行对象实例化时。
// 产品接口
interface Product {}// 具体产品类
class ConcreteProduct implements Product {}// 工厂接口
interface Creator {Product factoryMethod(); // 工厂方法,用于创建产品
}// 具体工厂类
class ConcreteCreator implements Creator {public Product factoryMethod() {return new ConcreteProduct(); // 返回具体产品实例}
}
3. 抽象工厂模式(Abstract Factory Pattern)
- 核心思想:提供一个接口,创建一系列相关或依赖对象,而无需指定具体类。
- 适用场景:需要创建一组相关或互相依赖的对象时。
// 抽象产品A
interface ProductA {}// 抽象产品B
interface ProductB {}// 具体产品A1
class ProductA1 implements ProductA {}// 具体产品B1
class ProductB1 implements ProductB {}// 抽象工厂接口
interface AbstractFactory {ProductA createProductA(); // 创建产品A的方法ProductB createProductB(); // 创建产品B的方法
}// 具体工厂1
class ConcreteFactory1 implements AbstractFactory {public ProductA createProductA() {return new ProductA1(); // 创建具体产品A1}public ProductB createProductB() {return new ProductB1(); // 创建具体产品B1}
}
4. 建造者模式(Builder Pattern)
- 核心思想:将一个复杂对象的构建与其表示分离,使得同样的构建过程可以创建不同的表示。
- 适用场景:需要构建复杂对象时,且构建过程独立于表示。
// 产品类
class Product {private String partA;private String partB;// 设置部件Apublic void setPartA(String partA) {this.partA = partA;}// 设置部件Bpublic void setPartB(String partB) {this.partB = partB;}
}// 建造者接口
interface Builder {void buildPartA(); // 构建部件Avoid buildPartB(); // 构建部件BProduct getResult(); // 获取构建的产品
}// 具体建造者
class ConcreteBuilder implements Builder {private Product product = new Product();public void buildPartA() {product.setPartA("PartA"); // 设置产品的部件A}public void buildPartB() {product.setPartB("PartB"); // 设置产品的部件B}public Product getResult() {return product; // 返回构建的产品}
}
5. 原型模式(Prototype Pattern)
- 核心思想:通过复制现有实例来创建新对象,避免重复初始化。
- 适用场景:需要大量相似对象时。
// 原型类
class Prototype implements Cloneable {// 克隆方法public Prototype clone() throws CloneNotSupportedException {return (Prototype) super.clone(); // 调用父类的克隆方法}
}
结构型模式
6. 适配器模式(Adapter Pattern)
- 核心思想:将一个类的接口转换成客户期望的另一个接口。
- 适用场景:接口不兼容但需要协同工作的类。
// 目标接口
interface Target {void request();
}// 被适配的类
class Adaptee {void specificRequest() {// 特殊请求}
}// 适配器类
class Adapter implements Target {private Adaptee adaptee;public Adapter(Adaptee adaptee) {this.adaptee = adaptee;}public void request() {adaptee.specificRequest(); // 转发请求到被适配对象}
}
7. 桥接模式(Bridge Pattern)
- 核心思想:将抽象部分与实现部分分离,使它们可以独立变化。
- 适用场景:需要跨越多个平台的对象。
// 实现接口
interface Implementor {void operationImpl();
}// 具体实现类A
class ConcreteImplementorA implements Implementor {public void operationImpl() {// 具体实现}
}// 抽象类
abstract class Abstraction {protected Implementor implementor;protected 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 Pattern)
- 核心思想:将对象组合成树形结构以表示“部分-整体”的层次结构。
- 适用场景:需要处理树形结构数据时。
// 组件接口
interface Component {void operation();
}// 叶子节点
class Leaf implements Component {public void operation() {// 叶子节点的操作}
}// 组合节点
class Composite implements Component {private List<Component> children = new ArrayList<>();// 添加子节点public void add(Component component) {children.add(component);}public void operation() {for (Component child : children) {child.operation(); // 递归调用子节点的操作}}
}
9. 装饰器模式(Decorator Pattern)
- 核心思想:动态地给对象添加一些额外的职责。
- 适用场景:需要扩展类的功能时。
// 组件接口
interface Component {void operation();
}// 具体组件
class ConcreteComponent implements Component {public void operation() {// 基本操作}
}// 装饰器抽象类
abstract class Decorator implements Component {protected Component component;protected Decorator(Component component) {this.component = component;}public void operation() {component.operation(); // 调用被装饰对象的操作}
}// 具体装饰器
class ConcreteDecorator extends Decorator {public ConcreteDecorator(Component component) {super(component);}public void operation() {super.operation();// 添加额外的操作}
}
10. 外观模式(Facade Pattern)
- 核心思想:为子系统中的一组接口提供一个一致的界面。
- 适用场景:简化复杂系统的使用。
// 子系统A
class SubsystemA {void operationA() {// 子系统A的操作}
}// 子系统B
class SubsystemB {void operationB() {// 子系统B的操作}
}// 外观类
class Facade {private SubsystemA subsystemA = new SubsystemA();private SubsystemB subsystemB = new SubsystemB();// 提供的统一接口void operation() {subsystemA.operationA(); // 调用子系统A的方法subsystemB.operationB(); // 调用子系统B的方法}
}
11. 享元模式(Flyweight Pattern)
- 核心思想:运用共享技术有效地支持大量细粒度对象。
- 适用场景:需要大量创建对象时,减少内存消耗。
// 享元类
class Flyweight {private String intrinsicState; // 内部状态public Flyweight(String intrinsicState) {this.intrinsicState = intrinsicState;}// 操作方法,传入外部状态void operation(String 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 Pattern)
- 核心思想:为其他对象提供一种代理,以控制对这个对象的访问。
- 适用场景:需要控制对象访问权限时。
// 抽象主题
interface Subject {void request();
}// 真实主题
class RealSubject implements Subject {public void request() {// 真实请求的处理}
}// 代理类
class Proxy implements Subject {private RealSubject realSubject;public void request() {if (realSubject == null) {realSubject = new RealSubject(); // 延迟初始化}realSubject.request(); // 转发请求}
}
行为型模式
13. 责任链模式(Chain of Responsibility Pattern)
- 核心思想:避免请求发送者与接收者耦合,让多个对象都有机会处理请求。
- 适用场景:请求需要多个对象处理时。
// 处理者抽象类
abstract class Handler {protected Handler successor; // 后继者// 设置后继者public void setSuccessor(Handler successor) {this.successor = successor;}// 处理请求public abstract void handleRequest();
}// 具体处理者1
class ConcreteHandler1 extends Handler {public void handleRequest() {if (successor != null) {successor.handleRequest(); // 转发请求}}
}
14. 命令模式(Command Pattern)
- 核心思想:将请求封装成对象,从而使你可用不同的请求对客户进行参数化。
- 适用场景:需要对请求排队、日志、撤销操作时。
// 命令接口
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 {void action() {// 执行动作}
}// 调用者
class Invoker {private Command command;// 设置命令public void setCommand(Command command) {this.command = command;}// 执行命令public void executeCommand() {command.execute();}
}
15. 解释器模式(Interpreter Pattern)
- 核心思想:为给定的语言定义文法表示,并定义一个解释器来处理这个文法。
- 适用场景:需要解释一种语言时。
// 表达式接口
interface Expression {int interpret();
}// 数字表达式
class Number implements Expression {private int number;public Number(int number) {this.number = number;}public int interpret() {return number; // 返回数字的值}
}// 加法表达式
class Plus implements Expression {private Expression leftOperand;private Expression rightOperand;public Plus(Expression left, Expression right) {this.leftOperand = left;this.rightOperand = right;}public int interpret() {return leftOperand.interpret() + rightOperand.interpret(); // 返回加法结果}
}
16. 迭代器模式(Iterator Pattern)
- 核心思想:提供一种方法顺序访问一个聚合对象中的各个元素,而不暴露其内部表示。
- 适用场景:需要遍历聚合对象时。
// 迭代器接口
interface Iterator {boolean hasNext(); // 是否有下一个元素Object next(); // 获取下一个元素
}// 聚合接口
interface Aggregate {Iterator createIterator(); // 创建迭代器
}// 具体聚合类
class ConcreteAggregate implements Aggregate {private List<Object> items = new ArrayList<>();public Iterator createIterator() {return new ConcreteIterator(this); // 创建具体迭代器}
}// 具体迭代器
class ConcreteIterator implements Iterator {private ConcreteAggregate aggregate;private int index;public ConcreteIterator(ConcreteAggregate aggregate) {this.aggregate = aggregate;}public boolean hasNext() {return index < aggregate.items.size(); // 判断是否有下一个元素}public Object next() {return aggregate.items.get(index++); // 返回下一个元素}
}
17. 中介者模式(Mediator Pattern)
- 核心思想:用一个中介对象来封装一系列对象的交互,使得对象之间不需要显式地相互引用。
- 适用场景:需要减少对象之间的依赖时。
// 中介者接口
interface Mediator {void notify(Component sender, String event); // 通知方法
}// 具体中介者
class ConcreteMediator implements Mediator {private Component1 component1;private Component2 component2;// 注册组件1public void registerComponent1(Component1 component) {this.component1 = component;}// 注册组件2public void registerComponent2(Component2 component) {this.component2 = component;}public void notify(Component sender, String event) {if (sender == component1 && event.equals("A")) {component2.doSomething(); // 组件1触发事件A,组件2响应} else if (sender == component2 && event.equals("B")) {component1.doSomething(); // 组件2触发事件B,组件1响应}}
}// 组件抽象类
abstract class Component {protected Mediator mediator;public Component(Mediator mediator) {this.mediator = mediator;}
}// 组件1
class Component1 extends Component {public Component1(Mediator mediator) {super(mediator);}public void doSomething() {mediator.notify(this, "A"); // 执行操作并通知中介者}
}// 组件2
class Component2 extends Component {public Component2(Mediator mediator) {super(mediator);}public void doSomething() {mediator.notify(this, "B"); // 执行操作并通知中介者}
}
18. 备忘录模式(Memento Pattern)
- 核心思想:在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。
- 适用场景:需要保存和恢复对象状态时。
// 备忘录类
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(); // 从备忘录恢复状态}
}// 管理者类
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 Pattern)
- 核心思想:定义对象间的一对多依赖关系,当一个对象状态改变时,所有依赖它的对象都得到通知并被自动更新。
- 适用场景:需要观察对象状态变化时。
// 观察者接口
interface Observer {void update(String state); // 更新方法
}// 具体观察者
class ConcreteObserver implements Observer {public void update(String state) {// 处理更新}
}// 主题类
class Subject {private List<Observer> observers = new ArrayList<>(); // 观察者列表private String state;public void attach(Observer observer) {observers.add(observer); // 添加观察者}public void setState(String state) {this.state = state;notifyAllObservers(); // 通知所有观察者}private void notifyAllObservers() {for (Observer observer : observers) {observer.update(state); // 更新观察者}}
}
20. 状态模式(State Pattern)
- 核心思想:允许对象在内部状态改变时改变它的行为。对象看起来似乎修改了它的类。
- 适用场景:对象状态改变时行为也改变时。
// 状态接口
interface State {void handle(Context context); // 处理方法
}// 具体状态A
class ConcreteStateA implements State {public void handle(Context context) {context.setState(new ConcreteStateB()); // 转换到状态B}
}// 具体状态B
class ConcreteStateB implements State {public void handle(Context context) {context.setState(new ConcreteStateA()); // 转换到状态A}
}// 上下文类
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 Pattern)
- 核心思想:定义一系列算法,把它们一个个封装起来,并且使它们可互相替换。
- 适用场景:需要动态选择算法时。
// 策略接口
interface Strategy {void execute(); // 执行方法
}// 具体策略A
class ConcreteStrategyA implements Strategy {public void execute() {// 策略A的实现}
}// 具体策略B
class ConcreteStrategyB implements Strategy {public void execute() {// 策略B的实现}
}// 上下文类
class Context {private Strategy strategy;public Context(Strategy strategy) {this.strategy = strategy; // 设置初始策略}public void setStrategy(Strategy strategy) {this.strategy = strategy; // 设置策略}public void executeStrategy() {strategy.execute(); // 执行策略}
}
22. 模板方法模式(Template Method Pattern)
- 核心思想:定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。
- 适用场景:多个类有相似算法时。
// 抽象类
abstract class AbstractClass {// 模板方法public final void templateMethod() {primitiveOperation1();primitiveOperation2();}// 基本操作1protected abstract void primitiveOperation1();// 基本操作2protected abstract void primitiveOperation2();
}// 具体类
class ConcreteClass extends AbstractClass {protected void primitiveOperation1() {// 实现基本操作1}protected void primitiveOperation2() {// 实现基本操作2}
}
23. 访问者模式(Visitor Pattern)
- 核心思想:将数据结构和作用于结构上的操作解耦,使得操作集合可独立变化。
- 适用场景:需要对对象结构中的对象实施多种操作时。
// 访问者接口
interface Visitor {void visit(ElementA element);void visit(ElementB element);
}// 元素接口
interface Element {void accept(Visitor visitor); // 接受访问者
}// 具体元素A
class ElementA implements Element {public void accept(Visitor visitor) {visitor.visit(this); // 接受访问者}
}// 具体元素B
class ElementB implements Element {public void accept(Visitor visitor) {visitor.visit(this); // 接受访问者}
}// 具体访问者
class ConcreteVisitor implements Visitor {public void visit(ElementA element) {// 访问元素A的操作}public void visit(ElementB element) {// 访问元素B的操作}
}
总结
设计模式为我们提供了一种标准化的解决方案,可以应对软件开发中常见的问题。通过理解和应用这些模式,我们可以编写出更具可维护性、可扩展性和可重用性的代码。希望这篇博客能帮助你更好地理解和使用设计模式。每种模式都有其独特的应用场景,选择合适的模式可以显著提高代码质量和开发效率。