第 7 章:23 种设计模式与 Spring 源码实践
大约 2 分钟
第 7 章:23 种设计模式与 Spring 源码实践
设计模式(Design Patterns)是资深软件工程师在面向对象设计中总结出的可复用最佳实践经验。
7.1 设计模式分类与 SOLID 七大原则
SOLID 七大设计原则
┌─────────────────────────────────────────────────────────────────────────────┐
│ 1. 单一职责原则 (SRP) - 一个类应该仅有一个引起它变化的原因 │
│ 2. 开闭原则 (OCP) - 对扩展开放,对修改关闭 (设计模式的灵魂) │
│ 3. 里氏替换原则 (LSP) - 子类必须能够替换任何基类出现的地方 │
│ 4. 接口隔离原则 (ISP) - 客户端不应被迫依赖它们不用的接口 │
│ 5. 依赖倒置原则 (DIP) - 高层模块不应依赖低层模块,二者都应依赖其抽象 │
└─────────────────────────────────────────────────────────────────────────────┘7.2 核心模式实战精讲
7.2.1 双重检查锁 (DCL) 单例模式
必须配合 volatile 关键字以禁止指令重排序:
public class Singleton {
// volatile 禁止编译期/CPU 指令重排序 (防止拿到未完成初始化的半成品对象)
private static volatile Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) { // 第一次检查:避免无谓加锁开销
synchronized (Singleton.class) {
if (instance == null) { // 第二次检查:保证线程安全
// 步骤 1: 分配内存 -> 步骤 2: 初始化对象 -> 步骤 3: 赋值给 instance
instance = new Singleton();
}
}
}
return instance;
}
}7.2.2 策略模式 (Strategy) + 工厂模式消除繁琐 if-else
在支付结算或规则计算场景中,使用策略模式解耦硬编码分支:
// 1. 定义统一策略接口
public interface PaymentStrategy {
void pay(double amount);
String getChannelCode(); // 策略唯一标识
}
// 2. 策略工厂容器 (配合 Spring @Component 自动注册)
@Component
public class PaymentStrategyFactory {
private final Map<String, PaymentStrategy> strategyMap = new ConcurrentHashMap<>();
// 利用 Spring 构造函数依赖注入,自动收集所有 PaymentStrategy 实现类!
public PaymentStrategyFactory(List<PaymentStrategy> strategies) {
for (PaymentStrategy strategy : strategies) {
strategyMap.put(strategy.getChannelCode(), strategy);
}
}
public PaymentStrategy getStrategy(String channelCode) {
PaymentStrategy strategy = strategyMap.get(channelCode);
if (strategy == null) {
throw new IllegalArgumentException("Unsupported payment channel: " + channelCode);
}
return strategy;
}
}7.2.3 责任链模式 (Chain of Responsibility)
用于工作流审批、请求拦截器链(如 Spring Security / Gateway Filter)。
7.3 Spring 框架中的设计模式经典应用
| 设计模式 | Spring 源码应用位置 |
|---|---|
| 工厂模式 (Factory) | BeanFactory / ApplicationContext 创建与管理 Bean 对象 |
| 单例模式 (Singleton) | Spring 单例 Bean 默认作用域 singletonObjects 一级缓存 |
| 代理模式 (Proxy) | Spring AOP 底层使用 JDK 动态代理与 CGLIB 代理 |
| 模板方法模式 (Template Method) | JdbcTemplate / RestTemplate 封装固定的准备与释放模板流程 |
| 观察者模式 (Observer) | ApplicationEventPublisher 消息发布与 @EventListener 监听器 |
| 适配器模式 (Adapter) | HandlerAdapter 适配分发不同类型的 Controller 处理器 |
