适配器模式
-
定义:
将一个接口转换成客户希望的另一个接口,使接口不兼容的那些类可以一起工作,别名为包装器(Wrapper)。适配器模式既可以作为类结构型模式,也可以作为对象结构型模式。
适配者模式中,通过增加一个新的适配器类来解决接口不兼容问题,使得原本没有任何关系的类可以协同工作。
根据适配器类和适配者类的关系不同,适配器模式可以分为对象适配器和类适配器两种,在对象适配器模式中,适配器与适配者之间使关联关系;在类适配器模式中,适配器与适配者之间是继承或者实现的关系。
-
使用场景:
- 系统需要使用一些现有的类,而这些类的接口不符合系统的需要,甚至没有这些类的源代码。
- 想创建一个可以重复使用的类,用于与一些彼此之间没有太大关联的一些类,包括一些可能在将来引进的类一起工作。
-
UML:
- AC:电压接口,output为电压输出方法。
- AC110、AC220:实现了AC接口的输出方法。
- DC5VAdapter:5V变压器适配器接口。
- ChinaPowerAdapter、JapanPowerAdapter:中国和日本的5V电压转换器。
-
优点:
- 将目标类和适配者类解耦,通过引入一个适配器类来重用现在的适配者类,无须修改原有结构。
- 增加了类的透明性和可复用性,将具体业务是按过程封装在适配器类中,对于客户端类而言是透明的,提高了适配者的复用性,同一适配者类可以在多个不同的系统中复用。
- 灵活性和扩展性都非常好,通过使用配置文件,可以很方便地更换适配器,也可以在不修改代码的基础上增加新的适配器类,完全符合开闭原则。
-
缺点:
- 对于Java、C#等不支持多重继承的语言,一次最多只能适配一个适配器类,不能同时适配多个适配者。
- 适配者类不能为最终类,如在Java中不能使用final类。
- 类适配器模式中的目标抽象类只能为接口,不能为类,其实用有一定的局限性。
-
样例:
public interface AC{ int outputAC() ; } public class AC110 implements AC{ public final int output = 110 ; @Override public int outputAC(){ return output ; } } public class AC220 implements AC{ public final int output = 220 ; @Override public int output(){ return output ; } }
public interface DC5VAdapter{ boolean support(AC ac) ; int outputDC5V(AC ac) ; }
public class ChinaPowerAdapter implements DC5VAdapter{ public static final int voltage = 220 ; @Override public boolean support(AC ac){ return voltage == ac.outputAC() ; } @Override public int outputDC5V(AC ac){ int adapterInput = ac.outputAC() ; int adapterOutput = adapterInput / 44 ; System.out.println("使用ChinaPowerAdapter变压适配器,输入AC:"+adapterInput+"V,输出DC:"+adapterOutput+"V。") ; return adapteOutput ; } } public class JapanPowerAdapter implements DC5VAdapter{ @Override public boolean support(AC ac){ return voltage == ac.outputAC() ; } @Override public int outputDC5V(AC ac){ int adapterInput = ac.outputAC() ; int adapterOutput = adapterInput / 22 ; System.out.println("使用ChinaPowerAdapter变压适配器,输入AC:"+adapterInput+"V,输出DC:"+adapterOutput+"V。") ; return adapterOutput ; } }
public class Test{ private List<DC5Adapter> adapters = new LinkedList<DC5Adapter>() ; public Test(){ this.adapters.add(new ChinaPowerAdapter()) ; this.adapters.add(new JapanPowerAdapter) ; } public DC5Adapter getPowerAdapter(AC ac){ DC5Adapter adapter = null ; for(DC5Adapter ad : this.adapters){ if(ad.support(ac)){ adapter = ad ; break ; } } if(adapter == null){ throw new IllegalArgumentException("没有找到何使的变压适配器"); } return adapter ; } public static void main(String[] args){ Test test = new Test() ; AC chinaAC = new AC220() ; DC5Adapter adapter = test.getPowerAdapter(chinaAC) ; AC japanAC = new AC110() ; adapter = test.getPowerAdapter(japanAC) ; adapter.outputDC5V(japanAC) ; } }