搬砖小弟
设计模式-适配器模式
2019-06-30 / 3 min read

定义

Convert the interface of a class into another interface clients expect.Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.(将一个类的接口变换成客户端所期待的另一种接口,从而使原本因接口不匹配而无法在一起工作的两个类能够在一起工作。)

UML图

代码实现

public interface Target {
     //目标角色有自己的方法
     public void request();
}
public class ConcreteTarget implements Target {
     public void request() {
             System.out.println("if you need any help,pls call me!");   }
}
public class Adaptee {
     //原有的业务逻辑
     public void doSomething(){
             System.out.println("I'm kind of busy,leave me alone,pls!");
     }
}
public class Adapter extends Adaptee implements Target {
     public void request() {
             super.doSomething();
     }
}
public class Client {
     public static void main(String[] args) {
             //原有的业务逻辑
             Target target = new ConcreteTarget();
             target.request();
             //现在增加了适配器角色后的业务逻辑
             Target target2 = new Adapter();
             target2.request();
     }
}

适配器模式的优点

  • 适配器模式可以让两个没有任何关系的类在一起运行,只要适配器这个角色能够搞定他们就成。
  • 增加了类的透明性
    想想看,我们访问的Target目标角色,但是具体的实现都委托给了源角色,而这些对高层次模块是透明的,也是它不需要关心的。
  • 提高了类的复用度
    当然了,源角色在原有的系统中还是可以正常使用,而在目标角色中也可以充当新的演员。
  • 灵活性非常好
    某一天,突然不想要适配器,没问题,删除掉这个适配器就可以了,其他的代码都不用修改,基本上就类似一个灵活的构件,想用就用,不想就卸载。

适配器模式的使用场景

适配器应用的场景只要记住一点就足够了:你有动机修改一个已经投产中的接口时,适配器模式可能是最适合你的模式。比如系统扩展了,需要使用一个已有或新建立的类,但这个类又不符合系统的接口,怎么办?使用适配器模式,这也是我们例子中提到的。