适配器模式 ⭐
定义
适配器模式(Adapter Pattern),将一个接口转换成客户端期望的另一个接口,使原本不兼容的接口可以一起工作。
- 转换插头(美标 → 国标)
- 翻译官(中文 → 英文)
符合的设计原则:
- 接口隔离(ISP):用户只用“自己需要的接口”
- 开放关闭(OCP):新增适配器,不改原代码
- 依赖倒置(DIP):依赖“统一接口”,不依赖具体实现
实现
js
const googleMap = {
show: function () {
console.log('开始渲染谷歌地图')
},
}
const baiduMap = {
display: function () {
console.log('开始渲染百度地图')
},
}
const baiduMapAdapter = {
show: function () {
return baiduMap.display()
},
}
const renderMap = function (map) {
if (map.show instanceof Function) {
map.show()
}
}
renderMap(googleMap)
renderMap(baiduMapAdapter)
执行结果
开始渲染谷歌地图
开始渲染百度地图
前端应用
1. 接口适配
js
// 后端
{ user_name: 'Tom', user_age: 20 }
// 前端统一
function formatUser(data) {
return {
name: data.user_name,
age: data.user_age
}
}
// A接口
{ list: [] }
// B接口
{ data: [] }
function adapter(res) {
return res.list || res.data
}
2. 浏览器兼容
js
const request = window.fetch
? fetch
: function (url) {
return new Promise((resolve) => {
const xhr = new XMLHttpRequest()
xhr.open('GET', url)
xhr.onload = () => resolve(xhr.response)
xhr.send()
})
}
3. 第三方库封装
js
function request(url) {
return axios.get(url)
}