js设计模式【详解】—— 桥接模式

桥接模式的定义

桥接模式:将抽象部分与它的实现部分分离,使它们都可以独立地变化。

使用场景:一个类存在两个或多个独立变化的维度,且这两个维度都需要进行扩展

优点:
把抽象与实现隔离开,有助于独立地管理各组成部分。


缺点:
每使用一个桥接元素都要增加一次函数调用,这对应用程序的性能会有一些负面影响——提高了系统的复杂程度。如果一个桥接函数被用于连接两个函数,而其中某个函数根本不会在桥接函数之外被调用,那么此时这个桥接函数就不是非要不可的。

演示范例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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

朝阳39

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值