🚀 Spring设计模式大揭秘:23种模式藏在你每天在用的框架里

130 阅读5分钟

🚀 Spring设计模式大揭秘:23种模式藏在你每天在用的框架里

🎯 引言

💡 设计模式太抽象?Spring源码来帮忙!

还在为设计模式的概念而头疼吗?还在觉得设计模式离实际开发太远吗?

今天,我们用Spring源码说话! 🎉

🎭 一个小故事

小王:"小李,你对Spring中的设计模式了解多少?"

小李:"额...我只知道几个概念,什么IoC、AOP、依赖注入,但具体用了什么设计模式完全不知道..."

小王"别慌! 其实你每天都在用Spring的设计模式,只是你不知道而已!"

小王:当你写 @Autowired 时,你在用依赖注入模式

小王:当你写 @Transactional 时,你在用代理模式

小王:当你写 ApplicationContext.getBean() 时,你在用工厂模式

小李"哇!原来Spring框架本身就是设计模式的集合?突然觉得也没那么神秘了!" 😄

本文将为您揭秘Spring框架中23种经典设计模式的真实应用场景。通过这个精心整理的对应表,您将发现:

  • 🎨 设计模式就在身边:每天使用的@Autowired@TransactionalApplicationContext等都在用设计模式
  • 🚀 从抽象到具体:让抽象的设计模式概念变得触手可及
  • 📚 最佳学习教材:Spring源码就是设计模式的最佳实践案例
  • 快速掌握技巧:一张表搞定23种设计模式,效率翻倍!

准备好了吗?让我们一起揭开Spring框架中设计模式的神秘面纱! 🔍

设计模式分类与Spring实现对照表

🎯 小贴士:这些设计模式就像"对象诞生的魔法师",负责创建和管理对象的生命周期

创建型模式(5种)

设计模式Spring中的具体应用核心类/接口(包名)
单例模式Bean作用域、ApplicationContextApplicationContext (org.springframework.context) BeanFactory (org.springframework.beans.factory) DefaultSingletonBeanRegistry (org.springframework.beans.factory.support)
工厂模式BeanFactory、ApplicationContext、FactoryBeanBeanFactory.getBean() (org.springframework.beans.factory) ApplicationContext.getBean() (org.springframework.context) FactoryBean.getObject() (org.springframework.beans.factory)
抽象工厂模式BeanDefinitionRegistry、BeanFactory层次结构BeanDefinitionRegistry (org.springframework.beans.factory.support) ListableBeanFactory (org.springframework.beans.factory) HierarchicalBeanFactory (org.springframework.beans.factory)
建造者模式BeanDefinitionBuilder、XmlBeanDefinitionReaderBeanDefinitionBuilder (org.springframework.beans.factory.support) XmlBeanDefinitionReader (org.springframework.beans.factory.xml)
原型模式Bean作用域prototype、Object.clone()Bean作用域prototype (org.springframework.beans.factory.config) AbstractBeanDefinition.cloneBeanDefinition() (org.springframework.beans.factory.support)

结构型模式(7种)

🏗️ 小贴士:这些设计模式就像"代码架构的魔法师",负责组织和管理对象之间的关系

设计模式Spring中的具体应用核心类/接口(包名)
适配器模式HandlerAdapter、AdvisorAdapterHandlerAdapter.handle() (org.springframework.web.servlet) AdvisorAdapter.getAdvice() (org.springframework.aop.framework.adapter)
装饰器模式BeanPostProcessor、BeanFactoryPostProcessorBeanPostProcessor.postProcessBeforeInitialization() (org.springframework.beans.factory.config) BeanFactoryPostProcessor.postProcessBeanFactory() (org.springframework.beans.factory.config)
代理模式AOP代理、JDK动态代理、CGLIB代理ProxyFactory (org.springframework.aop.framework) JdkDynamicAopProxy (org.springframework.aop.framework) CglibAopProxy (org.springframework.aop.framework)
桥接模式数据源桥接、事务管理器桥接DataSourceTransactionManager (org.springframework.jdbc.datasource) JpaTransactionManager (org.springframework.orm.jpa)
组合模式CompositeCacheManager、CompositeTransactionManagerCompositeCacheManager (org.springframework.cache.support) CompositeTransactionManager (org.springframework.transaction.support)
外观模式ApplicationContext、JdbcTemplateApplicationContext (org.springframework.context) JdbcTemplate (org.springframework.jdbc.core) TransactionTemplate (org.springframework.transaction.support)
享元模式Bean缓存、元数据缓存DefaultSingletonBeanRegistry.getSingleton() (org.springframework.beans.factory.support) CachedIntrospectionResults (org.springframework.core.type.classreading)

行为型模式(11种)

💃 小贴士:这些设计模式就像"对象协作的舞蹈家",负责协调对象之间的交互和通信

设计模式Spring中的具体应用核心类/接口(包名)
观察者模式ApplicationEvent、ApplicationListenerApplicationEvent (org.springframework.context.event) ApplicationListener (org.springframework.context.event)
策略模式TransactionManager、CacheManagerPlatformTransactionManager (org.springframework.transaction) CacheManager (org.springframework.cache)
命令模式CommandLineRunner、ApplicationRunnerCommandLineRunner.run() (org.springframework.boot) ApplicationRunner.run() (org.springframework.boot)
状态模式Bean生命周期状态、事务状态Bean生命周期状态管理 (org.springframework.beans.factory.config) TransactionStatus状态管理 (org.springframework.transaction)
模板方法模式JdbcTemplate、TransactionTemplateJdbcTemplate.execute() (org.springframework.jdbc.core) TransactionTemplate.execute() (org.springframework.transaction.support)
迭代器模式BeanDefinitionIterator、PropertySource迭代BeanDefinitionIterator (org.springframework.beans.factory.support) PropertySource迭代 (org.springframework.core.env)
责任链模式Filter链、Interceptor链FilterChain (org.springframework.web.filter) HandlerInterceptor链 (org.springframework.web.servlet)
中介者模式ApplicationContext组件通信ApplicationContext (org.springframework.context) BeanFactory组件通信 (org.springframework.beans.factory)
访问者模式BeanDefinitionVisitor、注解访问BeanDefinitionVisitor (org.springframework.beans.factory.support) 注解处理器 (org.springframework.core.annotation)
备忘录模式Bean状态保存、事务状态保存Bean状态管理 (org.springframework.beans.factory.config) TransactionStatus保存 (org.springframework.transaction)
解释器模式SpEL表达式解析、配置文件解析SpelExpressionParser (org.springframework.expression) 配置文件解析器 (org.springframework.core.io.support)

🧭 快速查找指南

🎯 快速导航小贴士:就像游戏里的地图,帮你快速找到想要的设计模式!

按功能查找

  • Bean管理:单例模式、工厂模式、建造者模式、原型模式
  • AOP功能:代理模式、装饰器模式、责任链模式
  • 事务管理:策略模式、状态模式、模板方法模式
  • 事件处理:观察者模式、命令模式

按包名查找(重点推荐)

  • org.springframework.beans.factory:单例模式、工厂模式、建造者模式、原型模式
  • org.springframework.aop:代理模式、装饰器模式、责任链模式
  • org.springframework.context:观察者模式、外观模式、中介者模式
  • org.springframework.transaction:策略模式、状态模式、模板方法模式

💡 小技巧:如果你经常用某个Spring模块,可以先从这个模块开始学习设计模式!

🌟 Spring设计模式实战案例

1. 单例模式 - Bean作用域管理

// Spring默认单例Bean
@Component
public class UserService {
    // 这个Bean在Spring容器中只有一个实例
}

// 通过@Scope指定作用域
@Component
@Scope("singleton"// 默认值,可以不写
public class OrderService {
    // 单例Bean
}

核心实现DefaultSingletonBeanRegistry.getSingleton()

2. 工厂模式 - BeanFactory

// 通过BeanFactory获取Bean
@Autowired
private BeanFactory beanFactory;

public void example() {
    UserService userService = beanFactory.getBean("userService", UserService.class);
    // 这就是工厂模式的应用
}

核心实现BeanFactory.getBean()

3. 代理模式 - AOP实现


@Service
@Transactional // 这个注解会创建代理对象
public class UserService {

    public void createUser(User user) {
        // 方法执行前会开启事务
        // 方法执行后会提交或回滚事务
    }
}

核心实现ProxyFactoryJdkDynamicAopProxyCglibAopProxy

4. 观察者模式 - 事件机制

// 发布事件
@Component
public class UserService {
    @Autowired
    private ApplicationEventPublisher eventPublisher;

    public void createUser(User user) {
        // 创建用户后发布事件
        eventPublisher.publishEvent(new UserCreatedEvent(user));
    }
}

// 监听事件
@Component
public class UserEventListener implements ApplicationListener<UserCreatedEvent> {

    @Override
    public void onApplicationEvent(UserCreatedEvent event) {
        // 处理用户创建事件
        System.out.println("用户创建了:" + event.getUser().getName());
    }
}

核心实现ApplicationEventPublisherApplicationListener

5. 策略模式 - 事务管理

// 不同的事务管理器策略
@Configuration
public class TransactionConfig {

    @Bean
    @Primary
    public PlatformTransactionManager jdbcTransactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean
    public PlatformTransactionManager jpaTransactionManager(EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
    }
}

核心实现PlatformTransactionManager接口的不同实现

🎉 总结

恭喜您! 🎊 现在您已经拥有了Spring框架中23种设计模式的完整地图!

💪 记住这句话

"Spring框架本身就是设计模式的活教材!学习Spring就是学习设计模式!"

🎭 一个小彩蛋

小王:小李,现在你对Spring中设计模式的理解怎么样?

小李"太棒了!现在我可以自信地说:我每天都在用Spring的设计模式!比如..."

小王:看来你已经掌握了Spring设计模式的精髓!

现在,您已经站在了Spring设计模式学习的制高点! 🏆


本文使用 markdown.com.cn 排版