适配器模式
来源:互联网 发布:fanuc pmc编程说明书 编辑:程序博客网 时间:2024/05/01 19:57
适配器模式
适配器模式属于结构型模式,这个模式将一个类的接口转换成客户希望的另外的一个接口。该模式使得原本两个不兼容的接口可以一起工作。
适配器模式适用于希望利用已经存在的功能,但是接口又和已经存在的功能不适配的情况。例如对于电源来说,假设现在有两种电源接口,一种输出电压是220V,另一种是110V的。现在只有220V的电源,怎么给110V的电器充电呢?此时可以利用电源适配器将220V的电压转换为110V的,这种其实就是利用了适配器模式的思想。
UML类图
如图所示,InterfaceOf110V
是110V电压电源的接口,InterfaceOf220V
是220V电压电源的接口, VoltageAdapter
是将220V电压电源转换为110V电压电源的适配器。接下来看具体代码实现:
代码实现
110V电压电源接口-InterfaceOf110V
/** * <p>文件描述: 110V电压接口</p> * * @Author luanmousheng * @Date 17/7/11 下午2:38*/public interface InterfaceOf110V { /** * 通过110V电压充电 */ void chargeWith110V();}
220V电压电源接口-InterfaceOf220V
/** * <p>文件描述: 220V电压接口</p> * * @Author luanmousheng * @Date 17/7/11 下午2:36*/public interface InterfaceOf220V { /** * 通过220V电压充电 */ void chargeWith220V();}
220V电压电源接口的实现-标准电压电源
/** * <p>文件描述: 标准电压(220V)</p> * * @Author luanmousheng * @Date 17/7/11 下午2:44*/public class StandardVoltage implements InterfaceOf220V{ @Override public void chargeWith220V() { System.out.println("标准220V充电"); }}
电源电压适配器-VoltageAdapter
/** * <p>文件描述: 电压适配器</p> * * @Author luanmousheng * @Date 17/7/11 下午3:02*/public class VoltageAdapter implements InterfaceOf110V { //需要适配的对象 private InterfaceOf220V standardVoltage = new StandardVoltage(); @Override public void chargeWith110V() { //将调用适配到standardVoltage standardVoltage.chargeWith220V(); System.out.println("适配器处理:适配220V到110V"); }}
适配器模式Demo
/** * <p>文件描述: 适配器Demo</p> * * @Author luanmousheng * @Date 17/7/11 下午3:05*/public class AdapterPatternDemo { public static void main(String[] args) { InterfaceOf110V interfaceOf110V = new VoltageAdapter(); interfaceOf110V.chargeWith110V(); }}
Demo转出为:
标准220V充电适配器处理:适配220V到110V
该例中原本110V和220V的电压电源是不兼容的,适配器模式利用了已经存在的接口(220V电压电源),复用已经存在的功能,适配器做的功能是将调用转到已经存在的功能上去。
阅读全文
0 0
- 适配器及适配器模式
- 适配器及适配器模式
- 适配器模式(类适配器)
- 适配器模式(默认适配器)
- 适配器模式(对象适配器)
- 适配器模式-类适配器
- 适配器模式-对象适配器
- 适配器模式
- 适配器模式
- 适配器模式
- 适配器模式
- 适配器模式
- 适配器模式
- 适配器模式
- 适配器模式
- 适配器模式
- 适配器模式
- 适配器模式
- IO流
- 51Nod X^2 Mod P
- python_函数(二)
- CART(Classification And Regression Tree)算法原理详解
- UDP协议
- 适配器模式
- 面向对象编程之单态设计模式
- Linux操作系统管理技术(三)
- 第一次用阿里云服务器,结果不能通过ip访问到云服务器
- Vue2.0的变化
- 链表的操作
- QJSON qt5.7.1+vs2015 WIN10编译
- [二分图匹配 线段树] Codeforces 573D Round #318 [RussianCodeCup Thanks-Round] (Div. 1) D. Bear and Cavalry
- Field获取java类中的成员变量名