适配器模式/Adapter Pattern
什么是适配器模式
适配器模式(Adapter Pattern)是作为两个不兼容的接口之间的桥梁。这种类型的设计模式属于结构型模式,它结合了两个独立接口的功能。
面向对象例子:
/**
* 将方法getFullSingaporeCityData返回的数据适配到
* getSingaporeCityData的格式
*/
class Adapter{
getSingaporeCityData() {
return {
shenggang: {
id: '0001',
coordinate: [1.3312, 103.32423]
},
fenwei: {
id: '0002',
coordinate: [1.3221, 103.1212]
},
angmokio: {
id: '0003',
coordinate: [1.654, 103.32465423]
}
}
}
getFullSingaporeCityData() {
return [
{
name: 'shenggang',
id: '0001',
coordinate: [1.3312, 103.32423],
peopleCount: 10000
},
{
name: 'fenwei',
id: '0002',
coordinate: [1.3312, 103.32423],
peopleCount: 20000
},
{
name: 'angmokio',
id: '0003',
coordinate: [1.3312, 103.32423],
peopleCount: 30000
}
]
}
dataAdapter(fn) {
let ret = {};
let list = fn();
list.forEach(function(v, k) {
let {name, ...props} = v;
ret[name] = {...props};
});
return function() {
return ret;
}
}
}