定义

  • 将抽象部分与它的实现部分分离,使它们都可以独立地变化。
  • 解耦

    根据javascript语言的特点,我们将其简化成2个角色:
    (1)扩充抽象类
    (2)具体实现类

    demo

    forEach函数的实现

    1. let each = function (arr, fn) {
    2. for (var i = 0; i < arr.length; i++) {
    3. var val = arr[i];
    4. if (fn.call(val, i, val, arr)) {
    5. return false;
    6. }
    7. }
    8. }

    解释

    抽象部分是each函数,也就是上面说的扩充抽象类,实现部分是fn,即具体实现类。抽象部分和实现部分可以独立的进行变化。这个例子虽然简单,但就是一个典型的桥接模式的应用。

    多维场景

    比如提取运动,着色,说话模块,球类可以具有运动和着色模块,人类可以具有运动和说话模块,

    demo

    运动模块

    1. class Speed { // 运动模块
    2. constructor(x, y) {
    3. this.x = x
    4. this.y = y
    5. }
    6. run() { console.log(`运动起来 ${this.x} + ${this.y}`) }
    7. }

    着色模块

    1. class Color { // 着色模块
    2. constructor(cl) {
    3. this.color = cl
    4. }
    5. draw() { console.log(`绘制颜色 ${this.color}`) }
    6. }
    7. }

    说话模块 ``javascript class Speak { // 说话模块 constructor(wd) { this.word = wd } say() { console.log(说话 ${this.word}`) } }

  1. **创建**
  2. ```javascript
  3. //人类
  4. class Man { // 人类,可以运动和说话
  5. constructor(x, y, wd) {
  6. this.speed = new Speed(x, y)
  7. this.speak = new Speak(wd)
  8. }
  9. init() {
  10. this.speed.run()
  11. this.speak.say()
  12. }
  13. }
  14. //球类
  15. class Ball { // 创建球类,可以着色和运动
  16. constructor(x, y, cl) {
  17. this.speed = new Speed(x, y)
  18. this.color = new Color(cl)
  19. }
  20. init() {
  21. this.speed.run()
  22. this.color.draw()
  23. }
  24. }

总结

优点

  • 分离接口和实现部分,一个实现未必不变地绑定在一个接口上,抽象类(函数)的实现可以在运行时刻进行配置,一个对象甚至可以在运行时刻改变它的实现,同将抽象和实现也进行了充分的解耦,也有利于分层,从而产生更好的结构化系统。
  • 提高可扩充性
  • 对客户隐藏实现细节。

    缺点

  • 大量的类将导致开发成本的增加,同时在性能方面可能也会有所减少。