1 概念
1 定义
将一个类的接口转换成客户期望的另一个接口。使得原本不兼容的类,可以一起工作
类型:结构型
分类:
对象适配器:使用组合
类适配器:使用类继承
2 适用场景
- 已经存在的类,他的方法和需求不匹配时(方法的结果相同或相似)
- 不是软件设计阶段考虑的设计模式,是随着软件的维护,由于不同产品,不同厂家造成功能类似而接口不相同情况下的解决方案
3 优缺点
优点:
- 提高类的透明性和复用,现有的类复用而不发生改变
- 目标类和适配器类解耦,提高程序扩展性
- 符合开闭原则
缺点:
增加代码可读性的难度
2 代码
场景:将220V直流电,通过充电器转换成5V的交流电,从而给手机充电
2.1 类适配器模式
1 2 3 4 5 6 7 8
| public class AC220 { public int outputAC220V(){ int output = 220; System.out.println("输出交流电"+output+"V"); return output; } }
|
1 2 3 4
| public interface DC5 { int outputDC5V(); }
|
1 2 3 4 5 6 7 8 9 10 11
| public class PowerAdapter extends AC220 implements DC5{ @Override public int outputDC5V() { int adapterInput = super.outputAC220V(); int adapterOutput = adapterInput/44; System.out.println("使用PowerAdapter输入AC:"+adapterInput+"V"+"输出DC:"+adapterOutput+"V"); return adapterOutput; } }
|
1 2 3 4 5 6
| public class Test { public static void main(String[] args) { Target adapterTarget = new Adapter(); adapterTarget.request(); } }
|
2.2 对象适配器
只有适配器的代码发生了改变
1 2 3 4 5 6 7 8 9 10 11 12 13
| public class PowerAdapter implements DC5{ private AC220 ac220 = new AC220();
@Override public int outputDC5V() { int adapterInput = ac220.outputAC220V(); int adapterOutput = adapterInput/44; System.out.println("使用PowerAdapter输入AC:"+adapterInput+"V"+"输出DC:"+adapterOutput+"V"); return adapterOutput; } }
|