在 TypeScript 中一般实现装饰器模式

时间:2020-12-30 00:15:13

标签: javascript typescript decorator

我正在尝试通用地实现运行时装饰器模式(不要与其他类型的装饰器混淆,尽管它们可以用于实现)。例如,在这个例子中,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
}

0 个答案:

没有答案