javaScript中的适配器模式

119 阅读1分钟

介绍

※ 旧接口格式和使用者不兼容

※ 中间加一个适配转换接口

实现代码(ES6)

class Adaptee{
    specificRequest(){       //原接口
        return '德国标准插头'
    }
}


class Target {            //转换类
    constructor(){
        this.adaptee = new Adaptee()
    }

    request(){              //转换方法
        let info = this.adaptee.specificRequest();
        return `${info} --- 转换器 --- 中国标准插头`
    }
} 

let target = new Target();

let res = target.request()
console.log(res)

举个栗子

● 适配器模式就像现实中的转换插头,一些普通插头做不到的事,转换插头可以帮你实现

设计原则

● 将旧接口和使用者进行分离

● 符合开放封闭原则