为了澄清,我使用的是https://refactoring.guru/design-patterns/decorator中的decorator 模式/方法,而不是TypeScript中的实验decorator 特性.
我正在try 在我的主类Foo
上扩展next
方法.
有几个功能由不同的类实现,如Bar
,Baz
...所以我觉得装饰者的模式就可以了.然而,问题是原始的next
方法可以在某些条件下调用自己.当它发生时,它当然调用原始next
而不是decorator next
.什么是正确的方法呢?我应该使用不同的模式吗?
interface IFoo {
next(): number;
}
class Foo implements IFoo {
next(): number {
console.log("Foo begin");
// ...
if (this.abc()) return this.next();
// ...
const result = this.xyz();
console.log("Foo end", result);
return result;
}
protected abc() {
return Math.random() < 0.5;
}
protected xyz(): number {
return Math.random();
}
}
class FooDecorator implements IFoo {
protected wrappee: IFoo;
constructor(wrappee: IFoo) {
this.wrappee = wrappee;
}
next() {
return this.wrappee.next();
}
}
class Bar extends FooDecorator {
next() {
console.log("Bar begin");
const result = this.wrappee.next() + 1;
console.log("Bar end", result);
return result;
}
}
let instance: IFoo = new Foo();
instance = new Bar(instance);
instance.next();