spring编程语言爱好者Java

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

2022-04-26  本文已影响0人  一只程序猿哟

Spring

控制反转IOC

依赖注入DI

工厂设计模式Factory

BeanFactory

ApplicationContext

单例设计模式Singleton

// 通过线程安全的concurrentHashMap实现单例注册表
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(64);

public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
    Assert.notNull(beanName, "'beanName' must not be null");
    synchronized(this.singletonObjects) {
        // 检查缓存中是否存在实例
        Object singletonObject = this.singletonObjects.get(beanName);
        if (singletonObject == null) {
            ...
            try {
                singleton = singletonFactory.getObject();
            }
            ...
            // 如果实例对象不存在,则将对象注册到单例注册表中
            addSingleton(beanName, singletonObject);
        }
        return (singletonObject != NULL_OBJECT ? singletonObject : null);
    }
}

protected void addSingleton(String beanName, Object singletonObject) {
    synchronized(this.singletonObjects) {
        this.singletonObjects.put(beanName, (singletonObject != null ? singletonObject : NULL_OBJECT));
    }
}
复制代码

代理设计模式Proxy

AOP中的代理模式

AspectJ和Spring AOP比较

AspectJ

Spring AOP

模板方法模式TemplateMethod

观察者模式Observer

Spring事件驱动模型

事件角色Event

事件监听者角色Listener

@FunctionalInterface
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
    void onApplicationEvent(E event);
}
复制代码

事件发布者角色Publisher

@FunctionalInterface
public interface ApplicationEventPublisher {
    default void publishEvent(ApplicationEvent event) {
        publishEvent((Object) event);
    }

    void publishEvent(Object event);
}
复制代码

Spring事件流程

适配器模式Adapter

Spring AOP中的适配器模式

Spring MVC中的适配器模式

装饰器模式Decorator

上一篇 下一篇

猜你喜欢

热点阅读