创建型模式(Creational Patterns)
1. 单例模式(Singleton Pattern)
意图:确保一个类只有一个实例,并提供一个全局的访问点。
要点:
- 保证全局只有一个对象实例。
- 控制实例化过程,避免重复创建。
下面展示6种常见的Java实现方式:
实现方式1:懒汉式(线程不安全)
1 2 3 4 5 6 7 8 9 10 11 12
| public class SingletonLazy { private static SingletonLazy instance;
private SingletonLazy() {}
public static SingletonLazy getInstance() { if (instance == null) { instance = new SingletonLazy(); } return instance; } }
|
缺点:在多线程环境下不安全。
实现方式2:懒汉式(线程安全,使用synchronized)
1 2 3 4 5 6 7 8 9 10 11 12
| public class SingletonLazySafe { private static SingletonLazySafe instance;
private SingletonLazySafe() {}
public static synchronized SingletonLazySafe getInstance() { if (instance == null) { instance = new SingletonLazySafe(); } return instance; } }
|
优点:线程安全,但加锁导致性能下降。
实现方式3:双重检查锁(DCL,Double-Check Locking)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| public class SingletonDCL { private volatile static SingletonDCL instance;
private SingletonDCL() {}
public static SingletonDCL getInstance() { if (instance == null) { synchronized (SingletonDCL.class) { if (instance == null) { instance = new SingletonDCL(); } } } return instance; } }
|
优点:线程安全且提高了一定性能。
实现方式4:静态内部类
1 2 3 4 5 6 7 8 9 10 11
| public class SingletonStaticInner { private SingletonStaticInner() {}
private static class Holder { private static final SingletonStaticInner INSTANCE = new SingletonStaticInner(); }
public static SingletonStaticInner getInstance() { return Holder.INSTANCE; } }
|
优点:利用类加载机制实现延迟加载,线程安全并且简单。
实现方式5:饿汉式(在类加载时就创建实例)
1 2 3 4 5 6 7 8 9
| public class SingletonHungry { private static final SingletonHungry INSTANCE = new SingletonHungry();
private SingletonHungry() {}
public static SingletonHungry getInstance() { return INSTANCE; } }
|
优点:简单,天生线程安全。缺点:不管用不用都会创建实例。
实现方式6:枚举式
1 2 3 4 5 6 7
| public enum SingletonEnum { INSTANCE;
public void doSomething() { System.out.println("Do something"); } }
|
优点:防反序列化和反射攻击的单例实现。
2. 工厂方法模式(Factory Method)
意图:定义一个创建对象的接口,但让子类决定实例化哪个类。
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| interface Product { void use(); }
class ConcreteProductA implements Product { public void use() { System.out.println("Use Product A"); } }
class ConcreteProductB implements Product { public void use() { System.out.println("Use Product B"); } }
abstract class Factory { public abstract Product createProduct(); }
class FactoryA extends Factory { public Product createProduct() { return new ConcreteProductA(); } }
class FactoryB extends Factory { public Product createProduct() { return new ConcreteProductB(); } }
|
3. 抽象工厂模式(Abstract Factory)
意图:提供一个接口用于创建相关或依赖对象的家族,而不需要指定具体类。
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| interface GUIFactory { Button createButton(); TextBox createTextBox(); }
interface Button { void click(); }
interface TextBox { void input(String text); }
class WinButton implements Button { public void click() { System.out.println("Windows Button Click"); } }
class WinTextBox implements TextBox { public void input(String text) { System.out.println("Windows TextBox input: " + text); } }
class MacButton implements Button { public void click() { System.out.println("Mac Button Click"); } }
class MacTextBox implements TextBox { public void input(String text) { System.out.println("Mac TextBox input: " + text); } }
class WinFactory implements GUIFactory { public Button createButton() { return new WinButton(); } public TextBox createTextBox() { return new WinTextBox(); } }
class MacFactory implements GUIFactory { public Button createButton() { return new MacButton(); } public TextBox createTextBox() { return new MacTextBox(); } }
|
4. 建造者模式(Builder)
意图:将一个复杂对象的构建与其表示分离,使得同样的构建过程可以创建不同的表示。
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| class Product { private String partA; private String partB;
public void setPartA(String partA) { this.partA = partA; } public void setPartB(String partB) { this.partB = partB; } public void show() { System.out.println("Product with " + partA + " and " + partB); } }
abstract class Builder { protected Product product = new Product(); public abstract void buildPartA(); public abstract void buildPartB(); public Product getResult() { return product; } }
class ConcreteBuilder extends Builder { public void buildPartA() { product.setPartA("A"); } public void buildPartB() { product.setPartB("B"); } }
class Director { public Product construct(Builder builder) { builder.buildPartA(); builder.buildPartB(); return builder.getResult(); } }
|
5. 原型模式(Prototype)
意图:用原型实例指定创建对象的种类,并通过拷贝这些原型创建新的对象。
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class Prototype implements Cloneable { private String field;
public Prototype(String field) { this.field = field; }
@Override protected Prototype clone() { try { return (Prototype) super.clone(); } catch (CloneNotSupportedException e) { return null; } }
public void show() { System.out.println("Field: " + field); } }
|
结构型模式(Structural Patterns)
6. 适配器模式(Adapter)
意图:将一个类的接口转换成客户希望的另一个接口,解决接口不兼容问题。
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| interface Target { void request(); }
class Adaptee { public void specificRequest() { System.out.println("Specific request"); } }
class Adapter implements Target { private Adaptee adaptee = new Adaptee(); public void request() { adaptee.specificRequest(); } }
|
7. 桥接模式(Bridge)
意图:将抽象部分与它的实现部分分离,使它们可以独立变化。
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| interface Implementor { void operationImpl(); }
class ConcreteImplementorA implements Implementor { public void operationImpl() { System.out.println("ConcreteImplementorA"); } }
class ConcreteImplementorB implements Implementor { public void operationImpl() { System.out.println("ConcreteImplementorB"); } }
abstract class Abstraction { protected Implementor imp; public Abstraction(Implementor imp) { this.imp = imp; } public abstract void operation(); }
class RefinedAbstraction extends Abstraction { public RefinedAbstraction(Implementor imp) { super(imp); } public void operation() { imp.operationImpl(); } }
|
8. 组合模式(Composite)
意图:将对象组合成树形结构以表示”部分-整体”层次结构。使得用户对单个对象和组合对象的使用具有一致性。
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| import java.util.ArrayList; import java.util.List;
interface Component { void operation(); }
class Leaf implements Component { public void operation() { System.out.println("Leaf operation"); } }
class CompositeNode implements Component { private List<Component> children = new ArrayList<>(); public void add(Component c) { children.add(c); } public void remove(Component c) { children.remove(c); } public void operation() { for (Component c : children) { c.operation(); } } }
|
9. 装饰器模式(Decorator)
意图:动态地给对象添加额外的职责。相比生成子类更灵活。
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| interface ComponentD { void operation(); }
class ConcreteComponent implements ComponentD { public void operation() { System.out.println("ConcreteComponent"); } }
abstract class Decorator implements ComponentD { protected ComponentD component; public Decorator(ComponentD component) { this.component = component; } public void operation() { component.operation(); } }
class ConcreteDecorator extends Decorator { public ConcreteDecorator(ComponentD component) { super(component); } public void operation() { super.operation(); System.out.println("Added behavior"); } }
|
10. 外观模式(Facade)
意图:为子系统中的一组接口提供一个一致的接口,提供简化的接口屏蔽复杂性。
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| class SubSystemA { public void methodA() { System.out.println("SubSystemA"); } }
class SubSystemB { public void methodB() { System.out.println("SubSystemB"); } }
class Facade { private SubSystemA a = new SubSystemA(); private SubSystemB b = new SubSystemB();
public void operate() { a.methodA(); b.methodB(); } }
|
11. 享元模式(Flyweight)
意图:运用共享技术有效地支持大量细粒度对象的重用。
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| import java.util.HashMap; import java.util.Map;
interface Flyweight { void operation(String extrinsicState); }
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); } }
class FlyweightFactory { private Map<String, Flyweight> pool = new HashMap<>();
public Flyweight getFlyweight(String key) { if (!pool.containsKey(key)) { pool.put(key, new ConcreteFlyweight(key)); } return pool.get(key); } }
|
12. 代理模式(Proxy)
意图:为其他对象提供一种代理以控制对这个对象的访问。
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| interface Subject { void request(); }
class RealSubject implements Subject { public void request() { System.out.println("RealSubject request"); } }
class Proxy implements Subject { private RealSubject realSubject; public void request() { if (realSubject == null) { realSubject = new RealSubject(); } System.out.println("Proxy before"); realSubject.request(); System.out.println("Proxy after"); } }
|
行为型模式(Behavioral Patterns)
13. 职责链模式(Chain of Responsibility)
意图:使多个对象都有机会处理请求,从而避免请求的发送者与接收者耦合在一起。
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| abstract class Handler { protected Handler next; public void setNext(Handler next) { this.next = next; } public abstract void handleRequest(int request); }
class ConcreteHandlerA extends Handler { public void handleRequest(int request) { if (request < 10) { System.out.println("A handled " + request); } else if (next != null) { next.handleRequest(request); } } }
class ConcreteHandlerB extends Handler { public void handleRequest(int request) { if (request >= 10) { System.out.println("B handled " + request); } else if (next != null) { next.handleRequest(request); } } }
|
14. 命令模式(Command)
意图:将请求封装成对象,从而使得可以用不同的请求对客户端进行参数化。
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| interface Command { void execute(); }
class Receiver { public void action() { System.out.println("Receiver action"); } }
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(); } }
|
15. 解释器模式(Interpreter)
意图:给定一门语言,定义它的文法的一种表示,并定义一个解释器来处理这种文法。
示例代码(简单示例,如解释加减表达式):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| interface Expression { int interpret(); }
class NumberExpression implements Expression { private int number; public NumberExpression(int number) { this.number = number; } public int interpret() { return number; } }
class PlusExpression implements Expression { private Expression left, right; public PlusExpression(Expression left, Expression right) { this.left = left; this.right = right; } public int interpret() { return left.interpret() + right.interpret(); } }
|
16. 迭代器模式(Iterator)
意图:提供一种方法顺序访问聚合对象的元素,而不暴露其内部表示。
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| interface IteratorX { boolean hasNext(); Object next(); }
interface Aggregate { IteratorX createIterator(); }
class ConcreteAggregate implements Aggregate { private String[] items = {"A", "B", "C"};
public IteratorX createIterator() { return new ConcreteIterator(items); } }
class ConcreteIterator implements IteratorX { private String[] items; private int index = 0; public ConcreteIterator(String[] items) { this.items = items; } public boolean hasNext() { return index < items.length; } public Object next() { return items[index++]; } }
|
意图:用一个中介对象来封装一系列对象交互,使对象不需要显式地互相引用,从而让它们松耦合。
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| abstract class Mediator { public abstract void sendMessage(String msg, Colleague colleague); }
abstract class Colleague { protected Mediator mediator; public Colleague(Mediator mediator) { this.mediator = mediator; } }
class ConcreteMediator extends Mediator { private ColleagueA a; private ColleagueB b; public void setColleagueA(ColleagueA a) { this.a = a; } public void setColleagueB(ColleagueB b) { this.b = b; }
public void sendMessage(String msg, Colleague colleague) { if (colleague == a) { b.notifyMessage(msg); } else { a.notifyMessage(msg); } } }
class ColleagueA extends Colleague { public ColleagueA(Mediator mediator) { super(mediator); } public void send(String msg) { mediator.sendMessage(msg, this); } public void notifyMessage(String msg) { System.out.println("A received: " + msg); } }
class ColleagueB extends Colleague { public ColleagueB(Mediator mediator) { super(mediator); } public void send(String msg) { mediator.sendMessage(msg, this); } public void notifyMessage(String msg) { System.out.println("B received: " + msg); } }
|
18. 备忘录模式(Memento)
意图:在不破坏封装性的前提下,捕获对象的内部状态,并在该对象之外保存这个状态,以便以后恢复。
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| 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 createMemento() { return new Memento(state); } public void restoreMemento(Memento m) { this.state = m.getState(); } }
class Caretaker { private Memento memento; public void saveMemento(Memento m) { this.memento = m; } public Memento getMemento() { return this.memento; } }
|
19. 观察者模式(Observer)
意图:定义对象间的一对多依赖,当一个对象发生改变时,其依赖者会收到通知自动更新。
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| import java.util.ArrayList; import java.util.List;
interface Observer { void update(String state); }
class ConcreteObserver implements Observer { private String name; public ConcreteObserver(String name) { this.name = name; } public void update(String state) { System.out.println(name + " received update: " + state); } }
class Subject { private List<Observer> observers = new ArrayList<>(); private String state;
public void attach(Observer o) { observers.add(o); } public void detach(Observer o) { observers.remove(o); }
public void setState(String state) { this.state = state; notifyAllObservers(); }
private void notifyAllObservers() { for (Observer o : observers) { o.update(state); } } }
|
20. 状态模式(State)
意图:允许对象在内部状态改变时改变其行为,对象看起来似乎修改了其类。
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| interface State { void handle(Context context); }
class ConcreteStateA implements State { public void handle(Context context) { System.out.println("State A"); context.setState(new ConcreteStateB()); } }
class ConcreteStateB implements State { public void handle(Context context) { System.out.println("State B"); context.setState(new ConcreteStateA()); } }
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)
意图:定义一系列算法,把它们分别封装起来,让它们可以互换使用。
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| interface Strategy { void algorithmInterface(); }
class ConcreteStrategyA implements Strategy { public void algorithmInterface() { System.out.println("Strategy A"); } }
class ConcreteStrategyB implements Strategy { public void algorithmInterface() { System.out.println("Strategy B"); } }
class ContextStrategy { private Strategy strategy; public ContextStrategy(Strategy strategy) { this.strategy = strategy; } public void setStrategy(Strategy strategy) { this.strategy = strategy; } public void executeStrategy() { strategy.algorithmInterface(); } }
|
22. 模板方法模式(Template Method)
意图:定义一个操作中的算法的框架,而将一些步骤延迟到子类中,使子类不改变算法结构即可重定义该算法的某些步骤。
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| abstract class AbstractClass { public final void templateMethod() { primitiveOperation1(); primitiveOperation2(); }
protected abstract void primitiveOperation1(); protected abstract void primitiveOperation2(); }
class ConcreteClass extends AbstractClass { protected void primitiveOperation1() { System.out.println("Operation1"); } protected void primitiveOperation2() { System.out.println("Operation2"); } }
|
23. 访问者模式(Visitor)
意图:表示一个作用于某对象结构中各元素的操作,使得可以在不改变各元素类的前提下定义作用于这些元素的新操作。
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| interface Element { void accept(Visitor visitor); }
class ConcreteElementA implements Element { public void accept(Visitor visitor) { visitor.visit(this); } public void operationA() { System.out.println("ElementA operation"); } }
class ConcreteElementB implements Element { public void accept(Visitor visitor) { visitor.visit(this); } public void operationB() { System.out.println("ElementB operation"); } }
interface Visitor { void visit(ConcreteElementA elementA); void visit(ConcreteElementB elementB); }
class ConcreteVisitor implements Visitor { public void visit(ConcreteElementA elementA) { elementA.operationA(); } public void visit(ConcreteElementB elementB) { elementB.operationB(); } }
class ObjectStructure { private List<Element> elements = new ArrayList<>(); public void add(Element element) { elements.add(element); } public void accept(Visitor visitor) { for (Element e : elements) { e.accept(visitor); } } }
|