Skip to main content

适配器模式

适配器模式:旧接口格式和使用者不兼容,中间加一个适配转换接口。

比如国外的插座跟国内的插座不一样,我们需要买个转换器去兼容。

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()

// 德国标准的插头 -> 转换器 -> 中国标准的插头

Demo

场景上可封装旧接口:

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

})

// 但因为历史原因,代码中全都是:
// $.ajax({...})

这个时候需要一个适配器:

// 做一层适配器
var $ = {
ajax: function (options) {
return ajax(options)
}
}