Typescript @Component "Decorator" 与装饰器模式有关吗?

Is the Typescript @Component "Decorator" related to the decorator pattern?

组件 .ts 文件中的 @Component({}) 行称为 Decorator。这与装饰器模式有关,还是无关?

它们是相关的,因为您用附加功能装饰现有的 class。它们不一样,因为typescript@Decorator是在编译时应用的,而decorator模式也可以在运行时用来装饰一个class,例如:

let armoredenemy = new Armored(new Enemy())
let enemy = new Enemy()

虽然程序是运行,但您仍然可以决定是否要装饰class。

打字稿装饰器:

现在是编译时间。这是一次但永久的改变,因为装饰的 class 与原来的 class 不同。而且很简单,基本上就是一个函数。

常见的场景是一个装饰器应用于不同的 classes。例如:在 Angular 中,@injector 装饰器应用于各种 classes 并使它们可注入。

对于一般装饰器模式:

常见的情况是在一个 class 上使用不同的装饰器。这非常繁重。您需要创建装饰器 class、装饰器 class 和原始装饰器 class 的公共父级 class 以及不同的子装饰器 class。原来的 class 保持不变,您可以在 运行 期间根据需要应用装饰器。

示例:您喝咖啡 class。您可以创建不同的装饰器 classes:Espresso、Cappuccino,如果您愿意,甚至可以创建 expresso + Cappuccino 咖啡。

只是我的 2 美分。