类图
代码
电压类(辅助类, 方便理解)
1 | /** |
110V电压类(目标类 Target)
1 | interface V110 extends Voltage{ |
220V电压类(辅助类, 方便理解)
1 | interface V220 extends Voltage{ |
电能(辅助类, 方便理解)
1 | class Power{ |
客户端类(Client)
1 | class Hotel{ |
德标电压类(ConcreteTarget,只是为了演示用)
1 | class GermanStandard implements V110{ |
中国标准电压类(Adaptee,被适配类)
1 | class ChineseStandard implements V220{ |
适配器类,核心(相当于Adapter类)
1 | class V220toV110 implements V110{ |
测试类
1 | public class Client { |
输出结果
1 | 德国宾馆开始使用电器:德国标准{电器电压=110V}} |
总结
概述
JAVA底层OutputStream有适配器ByteArrayOutputStream
注意: UML图和例子都是接口的适配,与正统的适配器模式略有差异
我举的这个例子可能有些繁琐,实际上核心就是一句话概括
德国宾馆用的插座电压是110V的,中国标准的电器的电话是220V的,为了让中国电器能在德国使用
中国标准电器 -> 适配器 -> 德国标准 -> 正常使用
优点
增加了被适配类的复用性