橋接模式
什么是橋接模式
把事物對(duì)象和其具體行為穿香、具體特征分離開(kāi)來(lái)才写,使它們可以各自獨(dú)立的變化
例子:
男生 女生
鋼琴 吉他
鋼琴能演奏驯用,吉他能演奏
男生能讓樂(lè)器演奏驼鞭,女生能讓樂(lè)器演奏
鋼琴是樂(lè)器, 吉他是樂(lè)器
需要一種方式讓對(duì)象和行為分離庶弃,便于隨意拼接
function Boy(instrument) {
this.sayHi = function() {
console.log('hi, 我是男生')
}
// 有一個(gè)功能叫playInstrument衫贬, 沒(méi)有具體樂(lè)器
this.playInstrument = function() {
instrument.play()
}
}
function Girl(instrument) {
this.sayHi = function() {
console.log('hi, 我是女生')
}
// 有一個(gè)功能叫playInstrument, 沒(méi)有具體樂(lè)器
this.playInstrument = function() {
instrument.play()
}
}
function Piano() {
this.play = function() {
console.log('鋼琴開(kāi)始演奏')
}
}
function Guitar() {
this.play = function() {
console.log('吉他開(kāi)始演奏')
}
}
let piano = new Piano()
let guitar = new Guitar()
let pianoBoy = new Boy(piano)
pianoBoy.playInstrument()
let guitarGirl = new Girl(guitar)
guitarGirl.playInstrument()
實(shí)際一點(diǎn)的案例
頁(yè)面有 Toast歇攻、Message 兩種形態(tài)的彈窗固惯,彈窗都有出現(xiàn)和隱藏等行為,這些行為可以使用不同風(fēng)格的動(dòng)畫缴守。
function Toast(node, animation) {
this.node = node
this.animation = animation
}
//調(diào)用 animation 的show方法
Toast.prototype.show = function() {
this.animation.show(this.node)
}
//調(diào)用 animation 的hide方法
Toast.prototype.hide = function() {
this.animation.hide(this.node)
}
function Message(node, animation) {
this.node = node
this.animation = animation
}
//調(diào)用 animation 的show方法
Message.prototype.show = function() {
this.animation.show(this.node)
}
//調(diào)用 animation 的hide方法
Message.prototype.hide = function() {
this.animation.hide(this.node)
}
const Animations = {
bounce: {
show: function(node) { console.log(node + '彈跳著出現(xiàn)') }
hide: function(node) { console.log(node + '彈跳著消失') }
},
slide: {
show: function(node) { console.log(node + '滑著出現(xiàn)') }
hide: function(node) { console.log(node + '滑著消失') }
}
}
let toast = new Toast('元素1', Animations.bounce )
toast.show()
let messageBox = new Message('元素2', Animations.slide)
messageBox.hide()