Appearance
桥接模式
将抽象与实现分离,两部分可以各自变化而不怕互相影响。
虽然各自独立,但是每使用一个桥接元素都要增加一次函数调用,这对性能有影响。
javascript
function Car1(engine){
this.engine = engine
}
Car1.prototype.platform = function(){
console.log("car1 stage")
}
Car1.prototype.loadEngine = function(){
this.engine.run()
}
function Car2(engine){
this.engine = engine
}
Car2.prototype.platform = function(){
console.log("car2 stage")
}
Car2.prototype.loadEngine = function(){
this.engine.run()
}
function engine1(){
this.run = function(){
console.log(engine1)
}
}
function engine2(){
this.run = function(){
console.log(engine2)
}
}
let car1 = new Car1(new engine1())
let car2 = new Car1(new engine2())
let car3 = new Car2(new engine1())
let car4 = new Car2(new engine2())
car1.platform()
car1.loadEngine()
car2.platform()
car2.loadEngine()
car3.platform()
car3.loadEngine()
car4.platform()
car4.loadEngine()
小例子
动画库,针对弹出型组件赋予多个不同的动画。弹出型组件有:modal, message, toast。动画假定有:bounce, slide, rotate
javascript
const Animations = {
bounce: {
show(ele){
console.log(ele, "弹跳显示")
},
hide(ele){
console.log(ele, "弹跳隐藏")
},
},
slide: {
show(ele){
console.log(ele, "滑动显示")
},
hide(ele){
console.log(ele, "滑动隐藏")
},
},
rotate: {
show(ele){
console.log(ele, "旋转显示")
},
hide(ele){
console.log(ele, "旋转隐藏")
},
}
}
function Toast(ele, animation){
this.ele = ele
this.animation = animation
}
Toast.prototype.show = function(){
// 抽象
this.animation.show(this.ele)
}
Toast.prototype.hide = function(){
// 抽象
this.animation.hide(this.ele)
}
let toast1 = new Toast("div1", Animations.bounce)
toast1.show()
setTimeout(()=>{
toast1.hide()
}, 1000)