桥接模式的定义
桥接模式:将抽象部分与它的实现部分分离,使它们都可以独立地变化。
使用场景:一个类存在两个或多个独立变化的维度,且这两个维度都需要进行扩展
优点:
把抽象与实现隔离开,有助于独立地管理各组成部分。
缺点:
每使用一个桥接元素都要增加一次函数调用,这对应用程序的性能会有一些负面影响——提高了系统的复杂程度。如果一个桥接函数被用于连接两个函数,而其中某个函数根本不会在桥接函数之外被调用,那么此时这个桥接函数就不是非要不可的。
演示范例1 —— 桥接模式实现演奏乐器
function Boy(instrument) {
this.sayHi = function() {
console.log('hi, 我是男生')
}
// 有一个功能叫playInstrument, 没有具体乐器
this.playInstrument = function() {
instrument.play()
}
}
function Girl(instrument) {
this.sayHi = function() {
console.log('hi, 我是女生')
}
// 有一个功能叫playInstrument, 没有具体乐器
this.playInstrument = function() {
instrument.play()
}
}
function Piano() {
this.play = function() {
console.log('钢琴开始演奏')
}
}
function Guitar() {
this.play = function() {
console.log('吉他开始演奏')
}
}
let piano = new Piano()
let guitar = new Guitar()
let pianoBoy = new Boy(piano)
pianoBoy.playInstrument()
let guitarGirl = new Girl(guitar)
guitarGirl.playInstrument()
男生、女生、钢琴、吉他各种独立,可以独立变化,通过桥接模式进行任意组合
演示范例2 —— 桥接模式实现不同弹窗不同动画
页面有 Toast、Message 两种形态的弹窗,弹窗都有出现和隐藏等行为,这些行为可以使用不同风格的动画。
function Toast(node, animation) {
this.node = node
this.animation = animation
}
//调用 animation 的show方法
Toast.prototype.show = function() {
this.animation.show(this.node)
}
//调用 animation 的hide方法
Toast.prototype.hide = function() {
this.animation.hide(this.node)
}
function Message(node, animation) {
this.node = node
this.animation = animation
}
//调用 animation 的show方法
Message.prototype.show = function() {
this.animation.show(this.node)
}
//调用 animation 的hide方法
Message.prototype.hide = function() {
this.animation.hide(this.node)
}
const Animations = {
bounce: {
show: function(node) { console.log(node + '弹跳着出现') }
hide: function(node) { console.log(node + '弹跳着消失') }
},
slide: {
show: function(node) { console.log(node + '滑着出现') }
hide: function(node) { console.log(node + '滑着消失') }
}
}
let toast = new Toast('元素1', Animations.bounce )
toast.show()
let messageBox = new Message('元素2', Animations.slide)
messageBox.hide()
更多设计模式详见——js设计模式【详解】总目录
https://blog.csdn.net/weixin_41192489/article/details/116154815