适用场景:
不同的对象(A,B)有相同的行为和特征,将这部分行为和特征单独出来,形成一个新的对象C,在构建对象(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