For clarity, I am utilizing the decorator pattern/approach from and not the experimental decorators feature in TypeScript.
The scenario involves extending the next
method on the main class Foo
. Various features are implemented by different classes like Bar
, Baz
... Hence, the decorator pattern seemed like a viable solution. However, there is an issue where the original next
method may call itself under certain conditions. In such cases, it ends up calling the original next
instead of the decorator's next
. What would be the correct approach in this scenario? Should I consider a different design pattern?
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();