前端设计模式 适配器模式

适配器模式:旧接口格式和使用者不兼容,中间加一个适配转换接口
比如国外的插座跟国内的插座不一样,我们需要买个转换器去兼容。
uml类图
代码
class Adaptee {
    specificRequest() {
        return '德国标准的插头';
    }
}

class Target {
    constructor() {
        this.adaptee = new Adaptee();
    }
    request() {
        let info = this.adaptee.specificRequest();
        return `${info} -> 转换器 -> 中国标准的插头`
    }
}

// 测试
let client = new Target();
client.request();



场景:封装旧接口
// 自己封装的ajax,使用方式如下:
ajax({
    url: '/getData',
    type: 'Post',
    dataType: 'json',
    data: {
        id: '123'
    }
}).done(function(){

})
// 但因为历史原因,代码中全都是:
// $.ajax({...})
这个时候需要一个适配器
// 做一层适配器
var $ = {
    ajax: function (options) {
        return ajax(options)
    }
}
原文地址:https://www.cnblogs.com/wzndkj/p/11781034.html