适配器模式是一种结构型的设计模式。它的主要作用是作为一个连接器实现不同方法或接口之间的兼容调用。
家里装过空调的朋友都知道,空调作为一种大功率的家用电器,接入线的功率和普通家用电器的接入线是不同的。普通电器的接入线为10A,但是空调的接入线是16A,普通家庭里的安装的插孔大多也都是10A,因此要解决这个问题,我们就需要一个支持输入端为10A,输出端为16A的插排。
// 电源
class ElectricSource {
constructor(){
this.power = 10;
}
getPower(){
return this.power;
}
}
//空调
class AirConditioner extends ElectricSource {
constructor(){
super();
this.needPower = 16;
}
tureOn(){
if(this.getPower() == this.needPower){
this.refrigerate();
} else {
console.log("power not match, can't run");
}
}
refrigerate(){
console.log('the air conditioner is refrigerating ');
}
}
let ac = new AirConditioner();
ac.tureOn(); // power not match, can't run
像上边那样两个类之间存在兼容问题,直接调用无法使程序正常运行,这时候只需要添加一个新的类作为适配器,作为两个类之间沟通的桥梁。
// 电源
class ElectricSource {
constructor() {
this.power = 10;
}
getPower() {
return this.power;
}
}
//空调
class AirConditioner {
constructor() {
this.needPower = 16;
}
tureOn() {
if (this.transedPower == this.needPower) {
this.refrigerate();
} else {
console.log("power not match, can't run");
}
}
setTransPower(power) {
this.transedPower = power;
}
refrigerate() {
console.log('the air conditioner is refrigerating ');
}
}
// 插排
class Interleaving {
connect(source, elecApp) {
this.transPower(source, elecApp);
}
transPower(source, elecApp) {
if (source.getPower() == 10) {
elecApp.setTransPower(16);
}
}
}
// 电源
let sourceObj = new ElectricSource();
// 空调
let acInstance = new AirConditioner();
// 插排
let adapter = new Interleaving();
// 连接
adapter.connect(sourceObj, acInstance);
// 打开空调
acInstance.tureOn(); // the air conditioner is refrigerating
这些适配器就像我们电脑上经常安装的驱动程序,它非常灵活,复用性也高。唯一的不足是当所适配的程序升级或更新时,适配器往往也需要视情况进行更新维护。