设计模式是软件工程中常见问题的解决方案模板。它们分为三大类:创建型模式、结构型模式和行为型模式。以下是26种常见的设计模式的分类和简要说明,以及每种模式的示例代码(以Java语言为例)。
创建型模式(Creational Patterns)
工厂方法模式(Factory Method):定义一个创建对象的接口,但让子类决定实例化哪个类。工厂方法使一个类的实例化延迟到其子类。
interface Product { }
class ConcreteProduct implements Product { }
interface Creator { Product factoryMethod(); }
class ConcreteCreator implements Creator { public Product factoryMethod() { return new ConcreteProduct(); } }
抽象工厂模式(Abstract Factory):提供一个接口,用于创建相关或依赖对象的家族,而不需要明确指定具体类。
interface AbstractFactory { ProductA createProductA(); ProductB createProductB(); }
class ConcreteFactory1 implements AbstractFactory { public ProductA createProductA() { return new ProductA1(); } public ProductB createProductB() { return new ProductB1(); } }
class ConcreteFactory2 implements AbstractFactory { public ProductA createProductA() { return new ProductA2(); } public ProductB createProductB() { return new ProductB2(); } }
单例模式(Singleton):确保一个类只有一个实例,并提供一个全局访问点。
class Singleton { private static Singleton instance = null; private Singleton() { } public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
建造者模式(Builder):将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
class Product { // 产品属性 }
class Builder { void buildPart() { /* … / } Product getResult() { / … / } }
class Director { void construct(Builder builder) { builder.buildPart(); } }
原型模式(Prototype):用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
class Prototype implements Cloneable { public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { return null; } } }
结构型模式(Structural Patterns)
适配器模式(Adapter):将一个类的接口转换成客户希望的另一个接口。适配器模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
class Adaptee { void specificRequest() { / … / } }
interface Target { void request(); }
class Adapter implements Target { private Adaptee adaptee; public Adapter(Adaptee adaptee) { this.adaptee = adaptee; } public void request() { adaptee.specificRequest(); } }
桥接模式(Bridge):将抽象部分与它的实现部分分离,使它们都可以独立地变化。
interface Implementor { void operationImpl(); }
abstract class Abstraction { protected Implementor implementor; public Abstraction(Implementor implementor) { this.implementor = implementor; } abstract void operation(); }
class RefinedAbstraction extends Abstraction { public RefinedAbstraction(Implementor implementor) { super(implementor); } public void operation() { implementor.operationImpl(); } }
组合模式(Composite):将对象组合成树形结构以表示“部分-整体”的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
interface Component { void operation(); }
class Leaf implements Component { public void operation() { / … / } }
class Composite implements Component { private List children = new ArrayList<>(); public void add(Component component) { children.add(component); } public void remove(Component component) { children.remove(component); } public void operation() { for (Component child : children) { child.operation(); } } }
装饰器模式(Decorator):动态地给一个对象添加一些额外的职责。就增加功能来说,装饰器模式相比生成子类更为灵活。
interface Component { void operation(); }
class ConcreteComponent implements Component { public void operation() { / … / } }
class Decorator implements Component { private 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(); } public void addedBehavior() { / … / } }
外观模式(Facade):为子系统中的一组接口提供一个一致的界面,外观模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。
class SubSystemOne { void methodOne() { / … / } }
class Facade { private SubSystemOne one; public Facade() { one = new SubSystemOne(); } public void facadeMethod() { one.methodOne(); / … / } }
享元模式(Flyweight):运用共享技术有效地支持大量细粒度的对象。
class Flyweight { void operation(String extrinsicState) { / … / } }
class FlyweightFactory { private HashMap<String, Flyweight> flyweights = new HashMap<>(); public Flyweight getFlyweight(String key) { if (!flyweights.containsKey(key)) { flyweights.put(key, new Flyweight()); } return flyweights.get(key); } }
代理模式(Proxy):为其他对象提供一种代理以控制对这个对象的访问。
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(); } }
行为型模式(Behavioral Patterns)
责任链模式(Chain of Responsibility):避免请求发送者与接收者耦合在一起,让多个对象都有可能接收请求,将这些对象连接成一条链,并且沿着这条链传递请求,直到有对象处理它为止。
abstract class Handler { protected Handler successor; public void setSuccessor(Handler successor) { this.successor = successor; } public abstract void handleRequest(int request); }
class ConcreteHandler1 extends Handler { public void handleRequest(int request) { if (request >= 0 && request < 10) { / … / } else if (successor != null) { successor.handleRequest(request); } } }
class ConcreteHandler2 extends Handler { public void handleRequest(int request) { if (request >= 10 && request < 20) { / … */ } else if (successor != null) { successor.handleRequest(request); } } }
命令模式(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 Invoker { private Command command; public void setCommand(Command command) { this.command = command; } public void invoke() { command.execute(); } }
解释器模式(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) { if (context.contains(data)) { return true; } return false; } }
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); } }
迭代器模式(Iterator):提供一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示。
interface Iterator { boolean hasNext(); Object next(); }
interface Aggregate { Iterator createIterator(); }
class ConcreteIterator implements Iterator { private ConcreteAggregate aggregate; private int index; public ConcreteIterator(ConcreteAggregate aggregate) { this.aggregate = aggregate; this.index = 0; }