引言
设计模式是软件设计的最佳实践。本文介绍常用设计模式的实现和应用。
一、创建型模式
1.1 单例模式
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 46 47 48 49 50
| public class Singleton1 { private static final Singleton1 INSTANCE = new Singleton1(); private Singleton1() {} public static Singleton1 getInstance() { return INSTANCE; } }
public class Singleton2 { private static volatile Singleton2 instance; private Singleton2() {} public static Singleton2 getInstance() { if (instance == null) { synchronized (Singleton2.class) { if (instance == null) { instance = new Singleton2(); } } } return instance; } }
public class Singleton3 { private Singleton3() {} private static class Holder { private static final Singleton3 INSTANCE = new Singleton3(); } public static Singleton3 getInstance() { return Holder.INSTANCE; } }
public enum Singleton4 { INSTANCE; public void doSomething() { System.out.println("Do something"); } }
|
1.2 工厂模式
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
| public class SimpleFactory { public static Product createProduct(String type) { if ("A".equals(type)) { return new ProductA(); } else if ("B".equals(type)) { return new ProductB(); } return null; } }
interface Factory { Product createProduct(); }
class FactoryA implements Factory { public Product createProduct() { return new ProductA(); } }
class FactoryB implements Factory { public Product createProduct() { return new ProductB(); } }
interface AbstractFactory { ProductA createProductA(); ProductB createProductB(); }
class ConcreteFactory1 implements AbstractFactory { public ProductA createProductA() { return new ProductA1(); } public ProductB createProductB() { return new ProductB1(); } }
|
1.3 建造者模式
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
| public class Person { private String name; private int age; private String address; private Person(Builder builder) { this.name = builder.name; this.age = builder.age; this.address = builder.address; } public static class Builder { private String name; private int age; private String address; public Builder name(String name) { this.name = name; return this; } public Builder age(int age) { this.age = age; return this; } public Builder address(String address) { this.address = address; return this; } public Person build() { return new Person(this); } } }
Person person = new Person.Builder() .name("Alice") .age(25) .address("Beijing") .build();
|
二、结构型模式
2.1 代理模式
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
| interface Subject { void request(); }
class RealSubject implements Subject { public void request() { System.out.println("Real request"); } }
class Proxy implements Subject { private RealSubject realSubject; public void request() { if (realSubject == null) { realSubject = new RealSubject(); } preRequest(); realSubject.request(); postRequest(); } private void preRequest() { System.out.println("Pre request"); } private void postRequest() { System.out.println("Post request"); } }
Subject proxy = (Subject) Proxy.newProxyInstance( RealSubject.class.getClassLoader(), new Class[]{Subject.class}, (proxy, method, args) -> { System.out.println("Before"); Object result = method.invoke(new RealSubject(), args); System.out.println("After"); return result; } );
|
2.2 装饰器模式
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
| interface Component { void operation(); }
class ConcreteComponent implements Component { public void operation() { System.out.println("Original operation"); } }
abstract class Decorator implements Component { protected Component component; public Decorator(Component component) { this.component = component; } }
class ConcreteDecorator extends Decorator { public ConcreteDecorator(Component component) { super(component); } public void operation() { component.operation(); addedFunction(); } private void addedFunction() { System.out.println("Added function"); } }
Component component = new ConcreteComponent(); component = new ConcreteDecorator(component); component.operation();
|
2.3 适配器模式
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
| interface Target { void request(); }
class Adaptee { public void specificRequest() { System.out.println("Specific request"); } }
class Adapter implements Target { private Adaptee adaptee; public Adapter(Adaptee adaptee) { this.adaptee = adaptee; } public void request() { adaptee.specificRequest(); } }
Target target = new Adapter(new Adaptee()); target.request();
|
三、行为型模式
3.1 观察者模式
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
| import java.util.ArrayList; import java.util.List;
interface Observer { void update(String message); }
class Subject { private List<Observer> observers = new ArrayList<>(); public void attach(Observer observer) { observers.add(observer); } public void detach(Observer observer) { observers.remove(observer); } public void notifyObservers(String message) { for (Observer observer : observers) { observer.update(message); } } }
class ConcreteObserver implements Observer { private String name; public ConcreteObserver(String name) { this.name = name; } public void update(String message) { System.out.println(name + " received: " + message); } }
Subject subject = new Subject(); subject.attach(new ConcreteObserver("Observer1")); subject.attach(new ConcreteObserver("Observer2")); subject.notifyObservers("Hello!");
|
3.2 策略模式
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
| interface Strategy { int calculate(int a, int b); }
class AddStrategy implements Strategy { public int calculate(int a, int b) { return a + b; } }
class SubtractStrategy implements Strategy { public int calculate(int a, int b) { return a - b; } }
class Context { private Strategy strategy; public Context(Strategy strategy) { this.strategy = strategy; } public void setStrategy(Strategy strategy) { this.strategy = strategy; } public int executeStrategy(int a, int b) { return strategy.calculate(a, b); } }
Context context = new Context(new AddStrategy()); System.out.println(context.executeStrategy(10, 5));
context.setStrategy(new SubtractStrategy()); System.out.println(context.executeStrategy(10, 5));
|
3.3 模板方法模式
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
| abstract class AbstractClass { public final void templateMethod() { step1(); step2(); step3(); } protected abstract void step1(); protected abstract void step2(); protected void step3() { System.out.println("Default step3"); } }
class ConcreteClass extends AbstractClass { protected void step1() { System.out.println("ConcreteClass step1"); } protected void step2() { System.out.println("ConcreteClass step2"); } }
AbstractClass obj = new ConcreteClass(); obj.templateMethod();
|
四、设计原则
- 单一职责原则(SRP):一个类只负责一个职责
- 开闭原则(OCP):对扩展开放,对修改关闭
- 里氏替换原则(LSP):子类可以替换父类
- 接口隔离原则(ISP):使用多个专门接口
- 依赖倒置原则(DIP):依赖抽象而非具体实现
- 迪米特法则(LOD):最少知识原则
- 合成复用原则(CRP):优先使用组合而非继承
总结
设计模式核心:
- 创建型:单例、工厂、建造者
- 结构型:代理、装饰器、适配器
- 行为型:观察者、策略、模板方法
- 原则:SOLID原则
参考资料
- 《设计模式:可复用面向对象软件的基础》
- 《Head First设计模式》