舊接口格式和使用者不兼容的狀況下須要加一個適配轉換接口,無須要改變舊的接口格式函數
eg: 電源適配器this
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
複製代碼