第506集设计模式实战
|字数总计:4.3k|阅读时长:20分钟|阅读量:
设计模式实战
1. 概述
1.1 设计模式的重要性
设计模式(Design Pattern)是面向对象软件设计中常见问题的解决方案,是代码设计经验的总结,能够提高代码的可维护性、可扩展性和可复用性。
本文内容:
- 创建型模式:单例、工厂、建造者、原型等模式
- 结构型模式:适配器、装饰器、代理、外观等模式
- 行为型模式:观察者、策略、责任链、模板方法等模式
- 实战应用:设计模式在实际项目中的应用场景
1.2 本文内容结构
本文将从以下几个方面深入探讨设计模式实战:
- 创建型模式:对象创建的设计模式
- 结构型模式:类和对象组合的设计模式
- 行为型模式:对象间通信的设计模式
- 模式组合:多种设计模式的组合使用
- 实战案例:设计模式在实际项目中的应用
2. 创建型模式
2.1 单例模式
2.1.1 单例模式实现
单例模式(Singleton):确保一个类只有一个实例,并提供全局访问点。
单例模式实现:
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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| public class EagerSingleton { private static final EagerSingleton instance = new EagerSingleton(); private EagerSingleton() {} public static EagerSingleton getInstance() { return instance; } }
public class LazySingleton { private static LazySingleton instance; private LazySingleton() {} public static LazySingleton getInstance() { if (instance == null) { instance = new LazySingleton(); } return instance; } }
public class DoubleCheckSingleton { private volatile static DoubleCheckSingleton instance; private DoubleCheckSingleton() {} public static DoubleCheckSingleton getInstance() { if (instance == null) { synchronized (DoubleCheckSingleton.class) { if (instance == null) { instance = new DoubleCheckSingleton(); } } } return instance; } }
public class StaticInnerClassSingleton { private StaticInnerClassSingleton() {} private static class SingletonHolder { private static final StaticInnerClassSingleton instance = new StaticInnerClassSingleton(); } public static StaticInnerClassSingleton getInstance() { return SingletonHolder.instance; } }
public enum EnumSingleton { INSTANCE; public void doSomething() { } }
|
2.2 工厂模式
2.2.1 简单工厂模式
简单工厂模式(Simple 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
| public interface Product { void use(); }
public class ConcreteProductA implements Product { @Override public void use() { System.out.println("Using Product A"); } }
public class ConcreteProductB implements Product { @Override public void use() { System.out.println("Using Product B"); } }
public class SimpleFactory { public static Product createProduct(String type) { if ("A".equals(type)) { return new ConcreteProductA(); } else if ("B".equals(type)) { return new ConcreteProductB(); } throw new IllegalArgumentException("Unknown product type"); } }
|
2.2.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 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| public interface Product { void use(); }
public class ConcreteProductA implements Product { @Override public void use() { System.out.println("Using Product A"); } }
public class ConcreteProductB implements Product { @Override public void use() { System.out.println("Using Product B"); } }
public interface Factory { Product createProduct(); }
public class ConcreteFactoryA implements Factory { @Override public Product createProduct() { return new ConcreteProductA(); } }
public class ConcreteFactoryB implements Factory { @Override public Product createProduct() { return new ConcreteProductB(); } }
|
2.2.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 39 40 41 42 43 44
| public interface ProductA { void useA(); }
public interface ProductB { void useB(); }
public class ConcreteProductA1 implements ProductA { @Override public void useA() { System.out.println("Using Product A1"); } }
public class ConcreteProductB1 implements ProductB { @Override public void useB() { System.out.println("Using Product B1"); } }
public interface AbstractFactory { ProductA createProductA(); ProductB createProductB(); }
public class ConcreteFactory1 implements AbstractFactory { @Override public ProductA createProductA() { return new ConcreteProductA1(); } @Override public ProductB createProductB() { return new ConcreteProductB1(); } }
|
2.3 建造者模式
2.3.1 建造者模式实现
建造者模式(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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| public class Product { private String partA; private String partB; private String partC; public String getPartA() { return partA; } public void setPartA(String partA) { this.partA = partA; } public String getPartB() { return partB; } public void setPartB(String partB) { this.partB = partB; } public String getPartC() { return partC; } public void setPartC(String partC) { this.partC = partC; } }
public interface Builder { Builder buildPartA(String partA); Builder buildPartB(String partB); Builder buildPartC(String partC); Product build(); }
public class ConcreteBuilder implements Builder { private Product product = new Product(); @Override public Builder buildPartA(String partA) { product.setPartA(partA); return this; } @Override public Builder buildPartB(String partB) { product.setPartB(partB); return this; } @Override public Builder buildPartC(String partC) { product.setPartC(partC); return this; } @Override public Product build() { return product; } }
public class Director { private Builder builder; public Director(Builder builder) { this.builder = builder; } public Product construct() { return builder .buildPartA("Part A") .buildPartB("Part B") .buildPartC("Part C") .build(); } }
|
2.4 原型模式
2.4.1 原型模式实现
原型模式(Prototype):用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
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
| public interface Prototype extends Cloneable { Prototype clone(); }
public class ConcretePrototype implements Prototype { private String field; public ConcretePrototype(String field) { this.field = field; } @Override public Prototype clone() { try { return (Prototype) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException("Clone failed", e); } } public String getField() { return field; } public void setField(String field) { this.field = field; } }
public class DeepPrototype implements Prototype { private String field; private ReferenceType reference; public DeepPrototype(String field, ReferenceType reference) { this.field = field; this.reference = reference; } @Override public Prototype clone() { DeepPrototype clone = null; try { clone = (DeepPrototype) super.clone(); clone.reference = reference.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException("Clone failed", e); } return clone; } }
|
3. 结构型模式
3.1 适配器模式
3.1.1 适配器模式实现
适配器模式(Adapter):将一个类的接口转换成客户希望的另一个接口。
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
| public interface Target { void request(); }
public class Adaptee { public void specificRequest() { System.out.println("Adaptee specific request"); } }
public class ClassAdapter extends Adaptee implements Target { @Override public void request() { specificRequest(); } }
public class ObjectAdapter implements Target { private Adaptee adaptee; public ObjectAdapter(Adaptee adaptee) { this.adaptee = adaptee; } @Override public void request() { adaptee.specificRequest(); } }
|
3.2 装饰器模式
3.2.1 装饰器模式实现
装饰器模式(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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| public interface Component { void operation(); }
public class ConcreteComponent implements Component { @Override public void operation() { System.out.println("ConcreteComponent operation"); } }
public abstract class Decorator implements Component { protected Component component; public Decorator(Component component) { this.component = component; } @Override public void operation() { component.operation(); } }
public class ConcreteDecoratorA extends Decorator { public ConcreteDecoratorA(Component component) { super(component); } @Override public void operation() { super.operation(); addedBehavior(); } private void addedBehavior() { System.out.println("Added behavior A"); } }
public class ConcreteDecoratorB extends Decorator { public ConcreteDecoratorB(Component component) { super(component); } @Override public void operation() { super.operation(); addedBehavior(); } private void addedBehavior() { System.out.println("Added behavior B"); } }
|
3.3 代理模式
3.3.1 代理模式实现
代理模式(Proxy):为其他对象提供一种代理以控制对这个对象的访问。
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 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| public interface Subject { void request(); }
public class RealSubject implements Subject { @Override public void request() { System.out.println("RealSubject request"); } }
public class Proxy implements Subject { private RealSubject realSubject; @Override 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"); } }
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy;
public class DynamicProxy implements InvocationHandler { private Object target; public DynamicProxy(Object target) { this.target = target; } public Object getProxy() { return Proxy.newProxyInstance( target.getClass().getClassLoader(), target.getClass().getInterfaces(), this ); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("Before method: " + method.getName()); Object result = method.invoke(target, args); System.out.println("After method: " + method.getName()); return result; } }
|
3.4 外观模式
3.4.1 外观模式实现
外观模式(Facade):为子系统中的一组接口提供一个统一的接口。
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
| public class SubsystemA { public void operationA() { System.out.println("SubsystemA operation"); } }
public class SubsystemB { public void operationB() { System.out.println("SubsystemB operation"); } }
public class SubsystemC { public void operationC() { System.out.println("SubsystemC operation"); } }
public class Facade { private SubsystemA subsystemA; private SubsystemB subsystemB; private SubsystemC subsystemC; public Facade() { this.subsystemA = new SubsystemA(); this.subsystemB = new SubsystemB(); this.subsystemC = new SubsystemC(); } public void operation() { subsystemA.operationA(); subsystemB.operationB(); subsystemC.operationC(); } }
|
4. 行为型模式
4.1 观察者模式
4.1.1 观察者模式实现
观察者模式(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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| import java.util.ArrayList; import java.util.List;
public interface Observer { void update(String message); }
public class ConcreteObserverA implements Observer { @Override public void update(String message) { System.out.println("ObserverA received: " + message); } }
public class ConcreteObserverB implements Observer { @Override public void update(String message) { System.out.println("ObserverB received: " + message); } }
public interface Subject { void attach(Observer observer); void detach(Observer observer); void notifyObservers(); }
public class ConcreteSubject implements Subject { private List<Observer> observers = new ArrayList<>(); private String state; @Override public void attach(Observer observer) { observers.add(observer); } @Override public void detach(Observer observer) { observers.remove(observer); } @Override public void notifyObservers() { for (Observer observer : observers) { observer.update(state); } } public void setState(String state) { this.state = state; notifyObservers(); } }
|
4.2 策略模式
4.2.1 策略模式实现
策略模式(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 25 26 27 28 29 30 31 32 33 34 35 36 37
| public interface Strategy { void execute(); }
public class ConcreteStrategyA implements Strategy { @Override public void execute() { System.out.println("Strategy A executed"); } }
public class ConcreteStrategyB implements Strategy { @Override public void execute() { System.out.println("Strategy B executed"); } }
public 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(); } }
|
4.3 责任链模式
4.3.1 责任链模式实现
责任链模式(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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| public abstract class Handler { protected Handler nextHandler; public void setNext(Handler handler) { this.nextHandler = handler; } public abstract void handleRequest(Request request); }
public class ConcreteHandlerA extends Handler { @Override public void handleRequest(Request request) { if (request.getType().equals("A")) { System.out.println("HandlerA handled request"); } else if (nextHandler != null) { nextHandler.handleRequest(request); } } }
public class ConcreteHandlerB extends Handler { @Override public void handleRequest(Request request) { if (request.getType().equals("B")) { System.out.println("HandlerB handled request"); } else if (nextHandler != null) { nextHandler.handleRequest(request); } } }
public class Request { private String type; public Request(String type) { this.type = type; } public String getType() { return type; } }
|
4.4 模板方法模式
4.4.1 模板方法模式实现
模板方法模式(Template 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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| public abstract class AbstractClass { public final void templateMethod() { step1(); step2(); step3(); } protected void step1() { System.out.println("Abstract step1"); } protected abstract void step2(); protected void step3() { System.out.println("Abstract step3"); } }
public class ConcreteClassA extends AbstractClass { @Override protected void step2() { System.out.println("ConcreteClassA step2"); } }
public class ConcreteClassB extends AbstractClass { @Override protected void step2() { System.out.println("ConcreteClassB step2"); } @Override protected void step3() { System.out.println("ConcreteClassB step3"); } }
|
4.5 命令模式
4.5.1 命令模式实现
命令模式(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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| public interface Command { void execute(); void undo(); }
public class ConcreteCommand implements Command { private Receiver receiver; public ConcreteCommand(Receiver receiver) { this.receiver = receiver; } @Override public void execute() { receiver.action(); } @Override public void undo() { receiver.undoAction(); } }
public class Receiver { public void action() { System.out.println("Receiver action"); } public void undoAction() { System.out.println("Receiver undo action"); } }
public class Invoker { private Command command; public void setCommand(Command command) { this.command = command; } public void executeCommand() { command.execute(); } }
|
5. 模式组合
5.1 模式组合使用
5.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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
|
public class StrategyFactory { public static Strategy createStrategy(String type) { switch (type) { case "A": return new ConcreteStrategyA(); case "B": return new ConcreteStrategyB(); default: throw new IllegalArgumentException("Unknown strategy type"); } } }
public class StrategyDecorator implements Strategy { private Strategy strategy; public StrategyDecorator(Strategy strategy) { this.strategy = strategy; } @Override public void execute() { System.out.println("Before strategy execution"); strategy.execute(); System.out.println("After strategy execution"); } }
public class StrategyContext implements Subject { private Strategy strategy; private List<Observer> observers = new ArrayList<>(); public void setStrategy(Strategy strategy) { this.strategy = strategy; notifyObservers(); } public void executeStrategy() { strategy.execute(); notifyObservers(); } @Override public void attach(Observer observer) { observers.add(observer); } @Override public void detach(Observer observer) { observers.remove(observer); } @Override public void notifyObservers() { for (Observer observer : observers) { observer.update("Strategy changed"); } } }
|
6. 实战案例
6.1 订单系统设计
6.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 51 52 53 54 55 56 57
| public class OrderFactory { public static Order createOrder(String orderType) { switch (orderType) { case "NORMAL": return new NormalOrder(); case "VIP": return new VipOrder(); case "DISCOUNT": return new DiscountOrder(); default: throw new IllegalArgumentException("Unknown order type"); } } }
public interface PriceStrategy { BigDecimal calculate(BigDecimal price); }
public class NormalPriceStrategy implements PriceStrategy { @Override public BigDecimal calculate(BigDecimal price) { return price; } }
public class VipPriceStrategy implements PriceStrategy { @Override public BigDecimal calculate(BigDecimal price) { return price.multiply(new BigDecimal("0.8")); } }
public class Order implements Subject { private OrderStatus status; private List<Observer> observers = new ArrayList<>(); public void setStatus(OrderStatus status) { this.status = status; notifyObservers(); } @Override public void attach(Observer observer) { observers.add(observer); } @Override public void notifyObservers() { for (Observer observer : observers) { observer.update("Order status changed to: " + status); } } }
|
6.2 缓存系统设计
6.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 44 45 46 47
| public class CacheManager { private static volatile CacheManager instance; private Map<String, Object> cache = new ConcurrentHashMap<>(); private CacheManager() {} public static CacheManager getInstance() { if (instance == null) { synchronized (CacheManager.class) { if (instance == null) { instance = new CacheManager(); } } } return instance; } public void put(String key, Object value) { cache.put(key, value); } public Object get(String key) { return cache.get(key); } }
public class CacheProxy implements DataService { private DataService realService; private CacheManager cacheManager; public CacheProxy(DataService realService) { this.realService = realService; this.cacheManager = CacheManager.getInstance(); } @Override public Object getData(String key) { Object data = cacheManager.get(key); if (data == null) { data = realService.getData(key); cacheManager.put(key, data); } return data; } }
|
7. 设计模式选择
7.1 模式选择原则
7.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
|
|
8. 总结
8.1 核心要点
- 创建型模式:关注对象创建,降低对象创建复杂度
- 结构型模式:关注类和对象的组合,形成更大的结构
- 行为型模式:关注对象间的通信和职责分配
- 模式组合:多种模式可以组合使用
- 模式选择:根据实际场景选择合适的模式
8.2 关键理解
- 设计模式本质:解决常见设计问题的经验总结
- 模式不是银弹:不要过度使用设计模式
- 模式组合:实际项目中往往需要组合多种模式
- 模式演进:理解模式原理,灵活应用
- 代码可读性:使用模式提高代码可维护性
8.3 最佳实践
- 理解原理:深入理解设计模式的原理和适用场景
- 适度使用:不要为了使用模式而使用模式
- 模式组合:根据实际需求组合使用多种模式
- 代码重构:使用设计模式重构现有代码
- 持续学习:不断学习新的设计模式和最佳实践
相关文章: