假如我们又这样软件系统,我们希望它能够和一个新的库搭配使用,但是这个库所提供的接口与我们的软件系统不兼容,我们不想改变现有代码就能解决这个问题,怎么办?这个时候我们就需要将这个新的库接口转换成我们所需要的接口,这就是适配器模式设计动机。
模式定义
所谓适配器模式?适配器模式就是将一个类的接口,转换成客户期望的另一个接口。适配器让原本不兼容的接口可以合作无间。
在适配器模式中,我们可以定义一个包装类,包装不兼容的类对象,这个包装类就是适配器Adapter,它所包装的对象就是适配者Adaptee。
适配器提供给客户需要的接口,适配器的实现就是调用的适配者的方法,将客户的请求转换成对适配者相应接口的引用。客户并不是直接访问适配者的方法,而是通过适配器去访问。
模式结构

适配者模式的四个角色
- Target:目标抽象类
- Adaptee:适配者
- Adapter:适配器
- Client:客户类
模式Demo
适配机器人例子
适配网线连接电脑使电脑可以上网的适配器
优缺点
- 将目标类和适配者类解耦,通过适配器让不兼容的接口变得兼容,让客户从实现的接口解耦
- 增加了类的透明性和适应性,将具体的实现封装在适配器中,对于客户端来说是透明的, 提高了适配者的复用性
-
使用场景
系统需要使用现有的类,而这些类不符合系统的需要
- 想要建里一个可以重复使用的类,用于与一些彼此之间没有太大关联的类
模式扩充
适配器模式分为对象适配和类适配。我们的demo中都是使用的对象适配。因为类适配需要使用继承,java只支持单继承,只能适配一个适配者,不灵活。
对象适配:一个对象适配器,可以把多个不同的适配者适配到同一个目标上,例如让机器人会小鸟叫,会小狗跑。
Spring中的应用
Spring的ApplicationListener接口是3.0中新增的,而4.0版本中有新增了GenericApplicationListener对ApplicationListener做了拓展,Spring在选择Listener的时候使用了适配器模式,方法代码如下
AbstractApplicationEventMulticaster#supportsEvent/*** Determine whether the given listener supports the given event.* <p>The default implementation detects the {@link SmartApplicationListener}* and {@link GenericApplicationListener} interfaces. In case of a standard* {@link ApplicationListener}, a {@link GenericApplicationListenerAdapter}* will be used to introspect the generically declared type of the target listener.* @param listener the target listener to check* @param eventType the event type to check against* @param sourceType the source type to check against* @return whether the given listener should be included in the candidates* for the given event type*/protected boolean supportsEvent(ApplicationListener<?> listener, ResolvableType eventType, @Nullable Class<?> sourceType) {GenericApplicationListener smartListener = (listener instanceof GenericApplicationListener ?(GenericApplicationListener) listener : new GenericApplicationListenerAdapter(listener));return (smartListener.supportsEventType(eventType) && smartListener.supportsSourceType(sourceType));}
该方法的意思是listener如果不属于GenericApplicationListener或者其子类的话,那么就肯定是ApplicationListener的子类SmartApplicationListener,那么就以组合的方式对SmartApplicationListener进行适配,在GenericApplicationListenerAdapter适配器中,对SmartApplicationListener进行适配,GenericApplicationListenerAdapter实现了GenericApplicationListener。
