【前端设计模式】装饰器模式

120 阅读1分钟

装饰器模式的作用

不生成子类的前提下,给现有对象添加新功能

标准装饰器模式

未命名文件(11).png

class Bracket {
  private str: string
  constructor(str: string) {
    this.str = str
  }
  draw(): string {
    return `(${this.str})`
  }
}

class Decorator {
  private bracket: Bracket
  constructor(bracket: Bracket) {
    this.bracket = bracket
  }
  draw(): string {
    return this.setBracket(this.bracket.draw()) // 装饰原有功能
  }
  private setBracket(str: string): string {
    return `{${str}}`
  }
}

const bracket = new Bracket('hi')
console.log(bracket.draw()) // (hi)

const decorator = new Decorator(bracket)
console.log(decorator.draw()) // {(hi)}

装饰器模式的应用

装饰器语法

// configurable装饰器
function configurable(val: boolean) {
  // target 实例, key 函数名, descriptor 属性描述符
  return function (target: any, key: string, descriptor: PropertyDescriptor) {
    descriptor.configurable = val
  }
}

class Test {
  private city = '西安'

  @configurable(false)
  getCity() {
    return this.city
  }
}

面向切面编程 (AOP, Aspect Oriented Program)

业务与系统基础功能分离。

function log(target: any, key: string, descriptor: PropertyDescriptor) {
  const oldValue = descriptor.value

  descriptor.value = function() {
    console.log('记录日志')
    return oldValue.apply(this, [arguments])
  }
}

class Test {
  @log // 不影响业务功能的代码,仅添加 log “切面”
  fn1() {
    console.log('业务功能')
  }
}

const test = new Test()
test.fn1()