版权声明:https://blog.csdn.net/qq_38270106 https://blog.csdn.net/qq_38270106/article/details/84724305
什么是适配器
在设计模式中,适配器模式(英语:adapter pattern)有时候也称包装样式或者包装(wrapper)。将一个类的接口转接成用户所期待的。一个适配使得因接口不兼容而不能在一起工作的类工作在一起,做法是将类自己的接口包裹在一个已存在的类中。
适配器分类
适配器分为,类适配器、对象适配、接口适配方式
类适配器方式采用继承方式,对象适配方式使用构造函数传递
适配器案例
我们就拿日本电饭煲的例子进行说明,日本电饭煲电源接口标准是110V电压,而中国标准电压接口是220V,所以要想在中国用日本电饭煲,需要一个电源转换器。
定义日本和中国两种接口及其实现
我们先定义日本220V电源接口和实现。
日本110V电源接口
public interface JP110VInterface {
void connect();
}
日本110V电源接口实现
public class JP110VInterfaceImpl implements JP110VInterface {
@Override
public void connect() {
System.out.println("日本110V,接通电源,开始工作..");
}
}
中国220V电源接口
public interface CN220VInterface {
void connect();
}
中国220V电源接口实现
public class CN220VInterfaceImpl implements CN220VInterface {
@Override
public void connect() {
System.out.println("中国220V,接通电源,开始工作...");
}
}
定义一个电饭煲
public class ElectricCook {
private JP110VInterface jP110VInterface;
// 接收110V的电源
public ElectricCook(JP110VInterface jP110VInterface) {
this.jP110VInterface = jP110VInterface;
System.out.println("电饭煲接收110V的电源...");
}
public void work() {
jP110VInterface.connect();
System.out.println("电饭煲开始工作...");
}
}
定义一个电压适配器
要想在中国使用日本电饭煲,需要把电饭煲110v的电源接口适配成我们220V的电源接口,这就需要一个电源适配器
public class PowerAdapter implements JP110VInterface {
private CN220VInterface cN220vInterface;
public PowerAdapter(CN220VInterface cN220vInterface) {
this.cN220vInterface = cN220vInterface;
System.out.println("适配器把220V的转换为110V的电源...");
}
@Override
public void connect() {
cN220vInterface.connect();
}
}
测试
public class Test {
public static void main(String[] args) {
CN220VInterface cN220VInterface = new CN220VInterfaceImpl();
PowerAdapter powerAdapter = new PowerAdapter(cN220VInterface);
ElectricCook electricCook = new ElectricCook(powerAdapter);
electricCook.work();
}
}
结果
适配器把220V的转换为110V的电源...
电饭煲接收110V的电源...
中国220V,接通电源,开始工作...
电饭煲开始工作...