定义:
将一个类的接口转换成客户希望的另一个接口。
角色:
target(目标对象):客户期望的目标对象,可以使具体对象或者接口 对应上图 中的厂商类
adaptee(需要适配的类):需要适配的类,上图中 现有的系统
adapter(适配器):适配器 把原接口转换成目标接口
方式:
常用有 类适配器 和 对象适配器
类适配器:采用继承实现
对象适配器 :采用组合实现
对象适配器:
例子:
老虎 ,猫, 想要把猫 伪装成老虎
target 目标接口:
public interface TargetService { public void say(); }
target的具体想要的结果:
public class Tiger implements TargetService { @Override public void say() { System.out.print("I am tiger."); } }
原目标:
public class Cat { public void say(){ System.out.print("I am cat."); } }
适配器:
public class Adapter implements TargetService { Cat cat; public Adapter(Cat cat) { this.cat = cat; } @Override public void say() { cat.say(); System.out.println(" but now I am tiger"); } }
客户端调用:
public class Client { public static void main(String[] args) { TargetService tiger = new Tiger(); tiger.say(); split(); Cat cat = new Cat(); cat.say(); split(); TargetService target = new Adapter(cat); target.say(); split(); } private static void split(){ System.out.println("\n---------------------------"); } }结果:
I am tiger.
---------------------------
I am cat.
---------------------------
I am cat. but now I am tiger
---------------------------
类适配器:
代码
适配器:
public class Adapter1 extends Cat implements TargetService { public void say(){ super.say(); System.out.println(" but now I am tiger"); } }
客户端:
public class Client1 { public static void main(String[] args) { TargetService tiger = new Tiger(); tiger.say(); split(); Cat cat = new Cat(); cat.say(); split(); TargetService target = new Adapter1(); target.say(); split(); } private static void split(){ System.out.println("\n---------------------------"); } }
执行结果:
I am tiger.
---------------------------
I am cat.
---------------------------
I am cat. but now I am tiger
---------------------------
优缺点:
优点:
1. 通过适配器,客户端可以调用同一个接口,对客户端是透明的,减少了调用的复杂性
2. 实现了类的复用,解决了现存的类 和 复用环境 要求不一致的问题
3. 通过引入适配器 ,将目标 类 和适配者类 进行解耦,通过引入适配器类实现 对 修改封闭
4. 对象适配器 使用组合 ,可以通过引入 适配者的抽象类,实现 把适配者的子类 都 适配到 目标接口
缺点:
对于对象适配器,更换适配器的实现比较麻烦
使用场景:
1. 系统需要使用已经现有的类,但是这些类 和目标接口不一致
2.两个类 所做的事情相同或者相似,但是具有不同的接口
3.旧的系统 已经实现了一些功能,但是客户端只能以另外的接口进行访问,但是我们不希望 更改原来的系统
4.使用 第三方组件,组件定义的接口 和己方接口不一致,不希望修改 原来的类,还想使用第三方接口
参考:
http://blog.youkuaiyun.com/jason0539/article/details/22468457