zhangdizhangdi

装饰器模式 ⭐

定义

装饰器模式(Decorator Pattern),在不改变对象自身的基础上,在程序运行期间给对象动态地添加职责。

实现

js
const before = function (fn, beforeFunc) {
  return function () {
    beforeFunc.apply(this, arguments)
    return fn.apply(this, arguments)
  }
}
const after = function (fn, afterFunc) {
  return function () {
    const ret = fn.apply(this, arguments)
    afterFunc.apply(this, arguments)
    return ret
  }
}
let a = before(
  function () {
    console.log(2)
  },
  function () {
    console.log(1)
  },
)
a = after(a, function () {
  console.log(3)
})
a()
执行结果
1
2
3
js
function readonly(target, name, descriptor) {
  descriptor.writable = false
  return descriptor
}

class Person {
  first = ''
  last = ''

  constructor() {
    this.first = 'A'
    this.last = 'B'
  }

  @readonly
  name() {
    return `${this.first} ${this.last}`
  }
}

let p = new Person()
console.log(p.name())
// p.name = function () {
//   console.log(100)
// } // Cannot assign to read only property 'name' of object '#<Person>'
js
function log(target, name, descriptor) {
  console.log(target)
  console.log(name)
  console.log(descriptor)

  let oldValue = descriptor.value
  descriptor.value = function () {
    console.log(`log: calling ${name} width`, arguments)
    return oldValue.apply(this, arguments)
  }
  return descriptor
}

class Math {
  @log
  add(a, b) {
    return a + b
  }
}
let math = new Math()
const result = math.add(4, 6)
console.log(result)

应用场景

  • AOP 面向切面编程,业务和系统基础功能分离(日志、统计、鉴权等)
  • 改变函数的参数
  • 表单验证

参考