Spring框架中都用到了哪些设计模式 ?

1.简单工厂模式

简单工厂模式的本质就是一个工厂类根据传入的参数,动态的决定实例化哪个类。Spring 中的 BeanFactory 就是简单工厂模式的体现,根据传入一个唯一的标识来获得 bean 对象。

2.工厂方法模式

应用程序将对象的创建及初始化职责交给工厂对象,工厂 Bean。定义工厂方法,然后通过 config.xml 配置文件,将其纳入 Spring 容器来管理,需要通过 factory-method 指定静态方法名称。

3.单例模式

Spring 用的是双重判断加锁的单例模式,通过 getSingleton 方法从 singletonObjects 中获取 bean。/**

* Return the (raw) singleton object registered under the given name.

* <p>Checks already instantiated singletons and also allows for an early

* reference to a currently created singleton (resolving a circular reference).

* @param beanName the name of the bean to look for

* @param allowEarlyReference whether early references should be created or not

* @return the registered singleton object, or {@code null} if none found

*/

protected Object getSingleton(String beanName, boolean allowEarlyReference) {

    Object singletonObject = this.singletonObjects.get(beanName);

    if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {

        synchronized (this.singletonObjects) {

            singletonObject = this.earlySingletonObjects.get(beanName);

            if (singletonObject == null && allowEarlyReference) {

                ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);

                if (singletonFactory != null) {

                    singletonObject = singletonFactory.getObject();

                    this.earlySingletonObjects.put(beanName, singletonObject);

                    this.singletonFactories.remove(beanName);

                }

            }

        }

    }

    return (singletonObject != NULL_OBJECT ? singletonObject : null);

}

4.代理模式

Spring 的 AOP 中,使用的 Advice(通知)来增强被代理类的功能。Spring 实现 AOP 功能的原理就是代理模式(① JDK 动态代理,② CGLIB 字节码生成技术代理。)对类进行方法级别的切面增强。

5.装饰器模式

装饰器模式:动态的给一个对象添加一些额外的功能。

Spring 的 ApplicationContext 中配置所有的 DataSource。这些 DataSource 可能是不同的数据库,然后 SessionFactory 根据用户的每次请求,将 DataSource 设置成不同的数据源,以达到切换数据源的目的。

在 Spring 中有两种表现:

一种是类名中含有 Wrapper;另一种是类名中含有 Decorator。

6. 观察者模式

定义对象间的一对多的关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并自动更新。Spring 中观察者模式一般用在 listener 的实现。

7.策略模式

策略模式是行为性模式,调用不同的方法,适应行为的变化 ,强调父类的调用子类的特性 。getHandler 是 HandlerMapping 接口中的唯一方法,用于根据请求找到匹配的处理器。

8.模板方法模式

Spring JdbcTemplate 的 query 方法总体结构是一个模板方法+回调函数,query 方法中调用的 execute()是一个模板方法,而预期的回调 doInStatement(Statement state)方法也是一个模板方法。

posted @   可爱的小锋  阅读(423)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)
· 全程使用 AI 从 0 到 1 写了个小工具
点击右上角即可分享
微信分享提示