如何解决在 TypeScript 中一般实现装饰器模式
我正在尝试通用地实现运行时装饰器模式(不要与其他类型的装饰器混淆,尽管它们可以用于实现)。例如,在这个例子中,BoomThingDecorator 是一个实际的具体装饰器,而 ThingDecorator 是一个方便的基类,定义为不必为这种类型的每个装饰器重复转发声明。我们可以为任何接口创建这样一个基本的装饰器类,而不是为我们想要装饰的每个类重复前向声明。我不确定这是否可行,因为 TypeScript 接口在运行时不存在。
interface IThing {
run(): void;
}
class Thing implements IThing {
run(): void {
null;
}
}
abstract class ThingDecorator implements IThing {
protected base: IThing;
constructor(base: IThing) {
this.base = base;
}
run(): void {
return this.base.run();
}
}
class BoomThingDecorator extends ThingDecorator {
boom(): number {
return 1;
}
}
例如类似的东西
abstract class Decorator<T> {
protected base: T;
constructor(base: T) { this.base = base; }
// something to forward all the methods of base
}
class BoomThingDecorator extends Decorator<IThing> {
// decorator methods
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。