JavaScript设计模式(十二):装饰者模式

198 阅读1分钟

介绍

装饰者模式:动态的给对象增加职责的方式。

这个跟代理模式有点像,区别是两者的目的不同。

  • 代理模式主要是直接访问对象本体时不方便,为本体对象提供一个替代者。
  • 装饰者模式主要是给本体对象动态的增加职责。

实现

const plane = function () {
  console.log('开火')
}
const missileDecorator = function () {
  console.log('发射导弹')
}
const DFDecorator = function () {
  console.log('发送快递')
}

const after = function (fn, afterFn) {
  return function () {
    fn.apply(this, arguments)
    afterFn.apply(this, arguments)
  }
}
const fire = after(after(plane, missileDecorator), DFDecorator)
fire() // 开火、发射导弹、发送快递

小结

装饰者模式可以给对象动态增加职责,方便我们对一些对象进行移植。