Spring中用到的设计模式
Spring 框架中使用了许多设计模式,这些设计模式帮助 Spring 实现了其强大的功能和灵活的配置。理解这些设计模式可以帮助开发者更好地理解和使用 Spring 框架。
1. 工厂模式(Factory Pattern)
场景说明:
在 Spring 中,BeanFactory 和 ApplicationContext 就是典型的工厂模式应用,它们负责创建和管理Bean对象,而不是让我们自己用 new 去实例化。
为什么要用工厂模式?
- 统一创建入口,方便扩展(修改一个地方就能替换整个系统的Bean创建方式)
- 支持解耦(调用者不关心具体实现类)
代码示例(模拟BeanFactory):
public interface Car {
void drive();
}
public class Tesla implements Car {
public void drive() {
System.out.println("Tesla is driving...");
}
}
public class CarFactory {
public static Car getCar(String type) {
if ("tesla".equalsIgnoreCase(type)) {
return new Tesla();
}
throw new IllegalArgumentException("Unknown car type");
}
}
Spring内部类似这样:我们通过配置文件或注解告诉它要什么Bean,Spring的工厂负责生产。
2. 单例模式(Singleton Pattern)
场景说明:
Spring默认Bean是单例的(scope="singleton"),也就是说在整个容器中,一种Bean只会有一个实例。
为什么要用单例?
- 节省内存,减少对象创建和GC压力
- 方便状态管理(但是要注意线程安全)
实际案例:
比如 Web 项目中的 UserService,用单例模式可以确保在整个系统中只维护一个业务层对象。
3. 代理模式(Proxy Pattern)
场景说明:
Spring AOP(如事务、日志、权限验证)几乎都是基于代理模式实现的。
为什么要用代理?
- 在不改变原有业务代码的情况下,动态为对象增强功能
- 可以在方法执行前后做额外逻辑
例子:
事务管理是典型案例,Spring会为业务类生成一个代理对象,在方法执行前开启事务,方法执行后提交或回滚。
简化演示:
public interface Service {
void doWork();
}
public class RealService implements Service {
public void doWork() {
System.out.println("Doing real work...");
}
}
public class ServiceProxy implements Service {
private Service target;
public ServiceProxy(Service target) {
this.target = target;
}
public void doWork() {
System.out.println("Transaction start");
target.doWork();
System.out.println("Transaction commit");
}
}
Spring在AOP里就是这么帮我们“包一层”。
4. 模板方法模式(Template Method Pattern)
场景说明:
Spring中很多抽象类其实是模板方法模式,比如 JdbcTemplate、AbstractApplicationContext。
它把一些过程的固定部分固化在抽象类中,把会变化的部分开放给子类重写。
实际案例:
JdbcTemplate.query() 统一了 JDBC 的获取连接、创建语句、关闭资源等,只需要传入不同的SQL和行处理函数就行。
5. 观察者模式(Observer Pattern)
场景说明:
Spring事件机制(ApplicationEvent、ApplicationListener)就是观察者模式。
当容器发布事件,所有订阅了该事件的监听器会自动收到通知。
实际案例:
用户注册成功事件 → 发送邮件通知 → 赠送优惠券,多个监听器独立处理。
6. 适配器模式(Adapter Pattern)
场景说明:
Spring MVC 的 HandlerAdapter 是典型的适配器模式,它把不同类型的 Handler 统一适配到 DispatcherServlet 可调用的方式。
课堂总结
给学员时可以这样说:
Spring源码不是随便写的,而是用了很多经典设计模式来解决实际问题:
- 工厂模式:统一创建Bean,解耦对象实例化
- 单例模式:节省资源
- 代理模式:动态增强功能(AOP、事务)
- 模板方法:固定流程 + 灵活定制
- 观察者模式:事件机制
- 适配器模式:统一接口调用方式
如果你理解这些模式,再看Spring源码就会发现它很“优雅”!

878

被折叠的 条评论
为什么被折叠?



