定义
- 将抽象部分与它的实现部分分离,使它们都可以独立地变化。
解耦
根据javascript语言的特点,我们将其简化成2个角色:
(1)扩充抽象类
(2)具体实现类demo
forEach函数的实现
let each = function (arr, fn) {for (var i = 0; i < arr.length; i++) {var val = arr[i];if (fn.call(val, i, val, arr)) {return false;}}}
解释
抽象部分是each函数,也就是上面说的扩充抽象类,实现部分是fn,即具体实现类。抽象部分和实现部分可以独立的进行变化。这个例子虽然简单,但就是一个典型的桥接模式的应用。
多维场景
比如提取运动,着色,说话模块,球类可以具有运动和着色模块,人类可以具有运动和说话模块,
demo
运动模块
class Speed { // 运动模块constructor(x, y) {this.x = xthis.y = y}run() { console.log(`运动起来 ${this.x} + ${this.y}`) }}
着色模块
class Color { // 着色模块constructor(cl) {this.color = cl}draw() { console.log(`绘制颜色 ${this.color}`) }}}
说话模块
``javascript class Speak { // 说话模块 constructor(wd) { this.word = wd } say() { console.log(说话 ${this.word}`) } }
**创建**```javascript//人类class Man { // 人类,可以运动和说话constructor(x, y, wd) {this.speed = new Speed(x, y)this.speak = new Speak(wd)}init() {this.speed.run()this.speak.say()}}//球类class Ball { // 创建球类,可以着色和运动constructor(x, y, cl) {this.speed = new Speed(x, y)this.color = new Color(cl)}init() {this.speed.run()this.color.draw()}}
