桥接模式(Bridge)将抽象部分与它的实现部分分离,使它们均可以独立地变化。
其实就是函数的封装,好比要对某个DOM元素添加color
和backgroundColor
,能够封装个changeColor
函数,这样能够在多个类似逻辑中提高智商...html
有时候在多维的变化中桥接模式更加实用,好比能够提取多个底层功能模块,好比提取运动,着色,说话模块,球类能够具备运动和着色模块,人类能够具备运动和说话模块,这样能够实现模块的快速组装,不单单是实现与抽象部分相分离了,而是更进一步功能与抽象相分离,进而 提高逼格 灵活的建立对象。前端
class Speed { // 运动模块 constructor(x, y) { this.x = x this.y = y } run() { console.log(`运动起来 ${this.x} + ${this.y}`) } } class Color { // 着色模块 constructor(cl) { this.color = cl } draw() { console.log(`绘制颜色 ${this.color}`) } } class Speak { constructor(wd) { this.word = wd } say() { console.log(`说话 ${this.word}`) } } class Ball { // 建立球类,能够着色和运动 constructor(x, y, cl) { this.speed = new Speed(x, y) this.color = new Color(cl) } init() { this.speed.run() this.color.draw() } } class Man { // 人类,能够运动和说话 constructor(x, y, wd) { this.speed = new Speed(x, y) this.speak = new Speak(wd) } init() { this.speed.run() this.speak.say() } } const man = new Man(1, 2, 'hehe?') man.init() // 运动起来 1 + 2 说话 hehe?
桥接模式的优势也很明显,咱们只列举主要几个优势:segmentfault
同时桥接模式也有本身的缺点:设计模式
本文是系列文章,能够相互参考印证,共同进步~缓存
网上的帖子大多深浅不一,甚至有些先后矛盾,在下的文章都是学习过程当中的总结,若是发现错误,欢迎留言指出~微信
参考:
设计模式之桥接模式
《Javascript 设计模式》 - 张荣铭
PS:欢迎你们关注个人公众号【前端下午茶】,一块儿加油吧~函数
另外能够加入「前端下午茶交流群」微信群,长按识别下面二维码便可加我好友,备注加群,我拉你入群~性能