JavaScript 适配器模式

112 阅读1分钟

20190721235234.png

1. JavaScript 适配器模式

旧接口格式和使用者不兼容的情况下需要加一个适配转换接口,无需要改变旧的接口格式

eg: 电源适配器

实现步骤

  • 针对 A 类创建一个 B 转换类
  • B 类中的 constructor 初始化中创建一个实例 instance
  • 利用类的多态特性覆盖 A 类的方法

代码实现

class 语法

class Plug {
    constructor(type) {
        this.type = type
    }
    getType() {
        return this.type
    }
}

class Adapter {
    constructor(oldType, newType) {
        this.plug = new Plug(oldType) // 初始化实例
        this.oldType = oldType
        this.newType = newType
    }
    getOldType() {
        return this.oldType
    }
    getType() { // 覆盖
        return this.newType
    }
}

let adapter = new Adapter('hdmi', 'typec')
let res = adapter.getType()
res // typec

res = adapter.getOldType()
res // hdmi

函数式

let hdmi = {
    getType() {
        return 'HDMI'
    }
}

let typeC = {
    getType() {
        return 'type-c'
    }
}

function typeCAdapter(plug) {
    return {
        getType() { // 覆盖
            return hdmi.getType()
        }
    }
}

res = typeCAdapter(typeC).getType()
res // HDMI