js设计模式-桥接模式
2019-08-13 本文已影响0人
hzl的学习小记
桥接模式
什么是桥接模式
把事物对象和其具体行为、具体特征分离开来,使它们可以各自独立的变化
例子:
男生 女生
钢琴 吉他
钢琴能演奏,吉他能演奏
男生能让乐器演奏,女生能让乐器演奏
钢琴是乐器, 吉他是乐器
需要一种方式让对象和行为分离,便于随意拼接
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()
实际一点的案例
页面有 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()