適用場景:
不同的對象(A,B)有相同的行爲和特徵,將這部分行爲和特徵單獨出來,形成一個新的對象©,在構建對象(A,B)時傳入對象C,對象(A,B)的行爲函數中調用對象C對應的行爲函數。
實際應用場景:
Toast、Message 兩種形態的彈窗,彈窗都有出現和隱藏等行爲。
下面用代碼實現一個最簡單的橋接模式
- ES5實現方式
function Toast(node, animation) {
this.node = node;
this.animation = animation
}
Toast.prototype.hide = function() {
this.animation.hide(this.node)
}
Toast.prototype.show = function() {
this.animation.show(this.node)
}
function Message(node, animation) {
this.node = node;
this.animation = animation;
this.hide = function() {
this.animation.hide(this.node)
}
this.show = function() {
this.animation.show(this.node)
}
}
Message.prototype.hide = function() {
this.animation.hide(this.node)
}
Message.prototype.show = function() {
this.animation.show(this.node)
}
const animation = {
hide: function(node) {
console.log(node, ' hide')
},
show: function(node) {
console.log(node, ' show')
}
}
let toast = new Toast('div', animation)
toast.show(); //div show
let message = new Message('div', animation)
message.hide() //div hide
- ES6實現方式
class Toast {
constructor(node, animation) {
this.node = node;
this.animation = animation
}
show() {
this.animation.show(this.node)
}
hide() {
this.animation.hide(this.node)
}
}
class Message{
constructor(node, animation) {
this.node = node;
this.animation = animation
}
show() {
this.animation.show(this.node)
}
hide() {
this.animation.hide(this.node)
}
}
class Animation {
constructor() {
}
hide(node) {
console.log(node, ' hide')
}
show(node) {
console.log(node, ' show')
}
}
let animation = new Animation()
let toast = new Toast('div', animation)
toast.show(); //div show
let message = new Message('div', animation)
message.hide() //div hide