JavaScript 设计模式-装饰器模式

装饰器模式 (我更倾向于叫 解耦模式)

  • 在继承(extends)没有语法上的实现之前常用
  • 在不改变原来的结构和功能基础上,动态装饰一些针对特别场景所适用的方法或属性,即添加一些新功能以增强它的某种能力
  • 原有方法维持不变,在原有方法上再挂载其他方法来满足现有需求;
  • 函数的解耦,将函数拆分成多个可复用的函数,再将拆分出来的函数挂载到某个函数上,
  • 实现相同的效果但增强了复用性。比如多孔插座,机车改装
const Man = function () {
  this.run = function () {
    console.info('跑步.')
  }
}

const Decorator = function (old) {
  this.oldAbility = old.run

  this.fly = function () {
    console.info('飞行')
  }

  this.newAbility = function () {
    this.oldAbility()
    this.fly()
  }
}

const man = new Man()

const superMan = new Decorator(man)
superMan.newAbility()

装饰器模式(使用类的继承的方式)

class SuperMan extends Man {
  fly() {
    console.info('I can fly.')
  }
  newAbility() {
    super.run()
    this.fly()
  }
}

const superMan = new SuperMan()
superMan.run()