适配器模式
适配器模式属于结构型模式,这个模式将一个类的接口转换成客户希望的另外的一个接口。该模式使得原本两个不兼容的接口可以一起工作。
适配器模式适用于希望利用已经存在的功能,但是接口又和已经存在的功能不适配的情况。例如对于电源来说,假设现在有两种电源接口,一种输出电压是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.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电压电源),复用已经存在的功能,适配器做的功能是将调用转到已经存在的功能上去。