简单工厂
![](https://i-blog.csdnimg.cn/blog_migrate/04054e0a89f6f1b0aa76a90dd312b48b.jpeg)
由一个工厂类根据传入的参数,动态决定应该创建哪一个产品类。
实现
BeanFactory
传入bean的名称,工厂返回对应bean对象,对应方法getBean(String name)
设计意义:
松耦合。 可以将原来硬编码的依赖,通过Spring这个beanFactory这个工厂来注入依赖,也就是说原来只有依赖方和被依赖方,现在我们引入了第三方——spring这个beanFactory,由它来解决bean之间的依赖问题,达到了松耦合的效果
单例模式
![](https://i-blog.csdnimg.cn/blog_migrate/fd59de0f0413ea514455560233be1a29.jpeg)
这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建
实现
Bean
Spring依赖注入Bean实例默认是单例的
public Object getSingleton(String beanName){
//参数true设置标识允许早期依赖
return getSingleton(beanName,true);
}
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
//检查缓存中是否存在实例
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
//如果为空,则锁定全局变量并进行处理。
synchronized (this.singletonObjects) {
//如果此bean正在加载,则不处理
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
//当某些方法需要提前初始化的时候则会调用addSingleFactory 方法将对应的ObjectFactory初始化策略存储在singletonFactories
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
//调用预先设定的getObject方法
singletonObject = singletonFactory.getObject();
//记录在缓存中,earlysingletonObjects和singletonFactories互斥
this.earlySingletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
}
}
}
}
return (singletonObject != NULL_OBJECT ? singletonObject : null);
}
设计意义
保证一个类仅有一个实例,并提供一个访问它的全局访问点。避免大量实例造成的浪费
适配器模式
![](https://i-blog.csdnimg.cn/blog_migrate/75d9745b712549a91d43b95d5f953058.png)
是作为两个不兼容的接口之间的桥梁。这种模式涉及到一个单一的类,该类负责加入独立的或不兼容的接口功能。
实现
SpringMVC中的适配器HandlerAdatper,连接了Handler和DispatcherServlet。
定义Handler的方式有很多:声明@RequestMapping、实现Controller接口、实现HttpRequestHandler。而通过实现HandlerAdatper实现对不同Handler的分别处理。
![](https://i-blog.csdnimg.cn/blog_migrate/7d8f38185464f054a23329096542d531.png)
设计意义
不同的Handler,处理请求的方式是不一样的,注解@RequestMapping方式使用的是用方法处理请求,而实现Controller接口和HttpRequestHandler接口方式使用的是一个类,而适配器模式就能模糊掉具体的实现,从而就能提供统一访问接口,所以这地方就要使用适配器了。
这样做的好处有两个
处理器程序,也就是Handler,允许的是任意的Object,只要返回封装好的HandlerExecutionChain,具体的Handler不用管
集成第三方请求处理器的时候,本处代码也无需修改,加个适配器就行
装饰器模式
![](https://i-blog.csdnimg.cn/blog_migrate/e903afb0c4594cedb3a6574d5c39fd05.png)
这种模式创建了一个装饰类,用来包装原有的类,并在保持类方法签名完整性的前提下,提供了额外的功能。
实现
Wrapper和Decorator
比如TransactionAwareCacheDecorator 类相当于装饰器模式中的抽象装饰角色,主要用来处理事务缓存
public class TransactionAwareCacheDecorator implements Cache {
private final Cache targetCache;
/**
* Create a new TransactionAwareCache for the given target Cache.
* @param targetCache the target Cache to decorate
*/
public TransactionAwareCacheDecorator(Cache targetCache) {
Assert.notNull(targetCache, "Target Cache must not be null");
this.targetCache = targetCache;
}
/**
* Return the target Cache that this Cache should delegate to.
*/
public Cache getTargetCache() {
return this.targetCache;
}
......
设计意义
不会相互耦合。是继承的一个替代模式,方便扩展功能