JavaScript设计模式——装饰器模式

112 阅读1分钟

介绍

装饰者模式,又称装饰器模式,在不改变原对象的基础上,通过对其添加属性或方法来进行包装拓展,使得原有对象可以动态具有更多功能。

js代码

class Component {
  operation() {
    console.log('基础组件操作');
  }
}

class Decorator {
  constructor(component) {
    this.component = component
  }

  operation() {
    this.component.operation()
    this.newOperation()
  }

  newOperation() {
    console.log('装饰器额外的操作')
  }
}

let component = new Component()
let decorator = new Decorator(component)
decorator.operation()

ts代码

// https://wangdoc.com/typescript/decorator
function simpleDecorator(
  value:any, // 当前类本身
  context:any // conetext.name 为字符串 class
) {
  console.log(`hi, this is ${context.kind} ${context.name}`);
  return value;
}

@simpleDecorator
class A {
  operation() {
    console.log('基础组件操作');
  }
}

const a = new A()

装饰器的语法有新旧的变化,代码使用较新的装饰器语法,详情请查看 阮一峰的 typescript 教程,装饰器