设计模式概述
设计模式是软件开发中常见问题的可重用解决方案,分为创建型、结构型和行为型三大类。以下是23种经典设计模式的简要说明及示例。
创建型模式
单例模式(Singleton)
确保一个类只有一个实例,并提供全局访问点。
java
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
工厂方法模式(Factory Method)
定义创建对象的接口,由子类决定实例化哪个类。
java
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();
}
抽象工厂模式(Abstract Factory)
提供一个接口,用于创建相关或依赖对象的家族。
java
public interface AbstractFactory {
ProductA createProductA();
ProductB createProductB();
}
建造者模式(Builder)
将一个复杂对象的构建与表示分离。
java
public class Product {
private String part1;
private String part2;
// Builder class implementation
}
原型模式(Prototype)
通过复制现有对象来创建新对象。
java
public interface Prototype {
Prototype clone();
}
结构型模式
适配器模式(Adapter)
将一个类的接口转换成客户希望的另一个接口。
java
public class Adapter implements Target {
private Adaptee adaptee;
public Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
public void request() {
adaptee.specificRequest();
}
}
桥接模式(Bridge)
将抽象部分与实现部分分离,使它们可以独立变化。
java
public abstract class Abstraction {
protected Implementor implementor;
public Abstraction(Implementor implementor) {
this.implementor = implementor;
}
public abstract void operation();
}
组合模式(Composite)
将对象组合成树形结构以表示"部分-整体"层次结构。
java
public interface Component {
void operation();
}
public class Leaf implements Component {
public void operation() {
System.out.println("Leaf operation");
}
}
装饰器模式(Decorator)
动态地给对象添加额外的职责。
java
public abstract class Decorator implements Component {
protected Component component;
public Decorator(Component component) {
this.component = component;
}
public void operation() {
component.operation();
}
}
外观模式(Facade)
为子系统中的一组接口提供一个统一的高层接口。
java
public class Facade {
private SubSystemA a;
private SubSystemB b;
public Facade() {
a = new SubSystemA();
b = new SubSystemB();
}
public void operation() {
a.operationA();
b.operationB();
}
}
享元模式(Flyweight)
运用共享技术有效地支持大量细粒度的对象。
java
public class FlyweightFactory {
private Map<String, Flyweight> flyweights = new HashMap<>();
public Flyweight getFlyweight(String key) {
if (!flyweights.containsKey(key)) {
flyweights.put(key, new ConcreteFlyweight(key));
}
return flyweights.get(key);
}
}
代理模式(Proxy)
为其他对象提供一种代理以控制对这个对象的访问。
java
public interface Subject {
void request();
}
public class Proxy implements Subject {
private RealSubject realSubject;
public void request() {
if (realSubject == null) {
realSubject = new RealSubject();
}
realSubject.request();
}
}
行为型模式
责任链模式(Chain of Responsibility)
让多个对象都有机会处理请求。
java
public abstract class Handler {
protected Handler successor;
public void setSuccessor(Handler successor) {
this.successor = successor;
}
public abstract void handleRequest(Request request);
}
命令模式(Command)
将请求封装为对象,支持请求的排队、日志和撤销。
java
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();
}
}
解释器模式(Interpreter)
定义语言的文法,并解释该语言中的句子。
java
public interface Expression {
boolean interpret(String context);
}
迭代器模式(Iterator)
提供一种方法顺序访问聚合对象的元素。
java
public interface Iterator {
boolean hasNext();
Object next();
}
中介者模式(Mediator)
定义一个中介对象来封装对象之间的交互。
java
public interface Mediator {
void notify(Colleague colleague, String message);
}
备忘录模式(Memento)
在不破坏封装性的前提下捕获对象的内部状态。
java
public class Memento {
private String state;
public Memento(String state) {
this.state = state;
}
public String getState() {
return state;
}
}
观察者模式(Observer)
定义对象间的一对多依赖关系,当一个对象状态改变时,所有依赖者都会收到通知。
java
public interface Observer {
void update();
}
public class ConcreteObserver implements Observer {
public void update() {
System.out.println("Observer updated");
}
}
状态模式(State)
允许对象在内部状态改变时改变其行为。
java
public interface State {
void handle(Context context);
}
策略模式(Strategy)
定义一系列算法,将每个算法封装起来,并使它们可以互换。
java
public interface Strategy {
void execute();
}
public class ConcreteStrategyA implements Strategy {
public void execute() {
System.out.println("Strategy A executed");
}
}
模板方法模式(Template Method)
定义一个操作中的算法骨架,将某些步骤延迟到子类中实现。
java
public abstract class AbstractClass {
public void templateMethod() {
primitiveOperation1();
primitiveOperation2();
}
protected abstract void primitiveOperation1();
protected abstract void primitiveOperation2();
}
访问者模式(Visitor)
在不改变各元素类的前提下定义作用于这些元素的新操作。
java
public interface Visitor {
void visit(ElementA elementA);
void visit(ElementB elementB);
}
public class ConcreteVisitor implements Visitor {
public void visit(ElementA elementA) {
System.out.println("Visited ElementA");
}
public void visit(ElementB elementB) {
System.out.println("Visited ElementB");
}
}