假如我们又这样软件系统,我们希望它能够和一个新的库搭配使用,但是这个库所提供的接口与我们的软件系统不兼容,我们不想改变现有代码就能解决这个问题,怎么办?这个时候我们就需要将这个新的库接口转换成我们所需要的接口,这就是适配器模式设计动机。

模式定义

所谓适配器模式?适配器模式就是将一个类的接口,转换成客户期望的另一个接口。适配器让原本不兼容的接口可以合作无间。

在适配器模式中,我们可以定义一个包装类,包装不兼容的类对象,这个包装类就是适配器Adapter,它所包装的对象就是适配者Adaptee。

适配器提供给客户需要的接口,适配器的实现就是调用的适配者的方法,将客户的请求转换成对适配者相应接口的引用。客户并不是直接访问适配者的方法,而是通过适配器去访问。

模式结构

适配器模式(Adapter Pattern) - 图1
适配者模式的四个角色

  1. 将目标类和适配者类解耦,通过适配器让不兼容的接口变得兼容,让客户从实现的接口解耦
  2. 增加了类的透明性和适应性,将具体的实现封装在适配器中,对于客户端来说是透明的, 提高了适配者的复用性
  3. 灵活性和扩展性都非常好,增加适配器不需要修改原有的代码

    使用场景

  4. 系统需要使用现有的类,而这些类不符合系统的需要

  5. 想要建里一个可以重复使用的类,用于与一些彼此之间没有太大关联的类

    模式扩充

    适配器模式分为对象适配和类适配。我们的demo中都是使用的对象适配。因为类适配需要使用继承,java只支持单继承,只能适配一个适配者,不灵活。

对象适配:一个对象适配器,可以把多个不同的适配者适配到同一个目标上,例如让机器人会小鸟叫,会小狗跑。

Spring中的应用

Spring的ApplicationListener接口是3.0中新增的,而4.0版本中有新增了GenericApplicationListener对ApplicationListener做了拓展,Spring在选择Listener的时候使用了适配器模式,方法代码如下

  1. AbstractApplicationEventMulticaster#supportsEvent
  2. /**
  3. * Determine whether the given listener supports the given event.
  4. * <p>The default implementation detects the {@link SmartApplicationListener}
  5. * and {@link GenericApplicationListener} interfaces. In case of a standard
  6. * {@link ApplicationListener}, a {@link GenericApplicationListenerAdapter}
  7. * will be used to introspect the generically declared type of the target listener.
  8. * @param listener the target listener to check
  9. * @param eventType the event type to check against
  10. * @param sourceType the source type to check against
  11. * @return whether the given listener should be included in the candidates
  12. * for the given event type
  13. */
  14. protected boolean supportsEvent(
  15. ApplicationListener<?> listener, ResolvableType eventType, @Nullable Class<?> sourceType) {
  16. GenericApplicationListener smartListener = (listener instanceof GenericApplicationListener ?
  17. (GenericApplicationListener) listener : new GenericApplicationListenerAdapter(listener));
  18. return (smartListener.supportsEventType(eventType) && smartListener.supportsSourceType(sourceType));
  19. }

该方法的意思是listener如果不属于GenericApplicationListener或者其子类的话,那么就肯定是ApplicationListener的子类SmartApplicationListener,那么就以组合的方式对SmartApplicationListener进行适配,在GenericApplicationListenerAdapter适配器中,对SmartApplicationListener进行适配,GenericApplicationListenerAdapter实现了GenericApplicationListener。