首页 > 解决方案 > 打字稿中的增强抽象方法

问题描述

我有Command抽象方法“ execute()”的抽象类。许多其他命令扩展了它。每个都有自己的“ execute()”实现。

每次执行任何命令时,如何添加一些通用逻辑(如日志记录)?

export abstract class Command {
    public abstract execute(...commandParams: any[]): void;
}

标签: javascripttypescriptabstract-classcommand-pattern

解决方案


在我看来,处理这个问题的最好方法是在你调用execute 方法的地方,而不是在方法本身内部。

您不会对execute函数参数进行良好的类型检查,因为它们被定义为...commandParams: any[]. 这是一个我们可以利用泛型来强制所有Command类型都适合通用接口的地方,同时也不会丢失有关其唯一参数的信息。

仅供参考,这也可以是 ainterface而不是abstract class.

interface Command<T extends any[]> {
    execute( ...commandParams: T): void;
    toString(): string;
}

class Executer {
    execute<T extends any[]>( command: Command<T>, ...args: T ) {
        command.execute(...args);
    }
    
    executeAndLog<T extends any[]>( command: Command<T>, ...args: T ) {
        console.log( `executing command ${command.toString()} with arguments:`, ...args );
        command.execute(...args);
    }
}

游乐场链接

T中的泛型Executer表示我们可以传入任何类型的Command,但参数必须与该特定命令类型的预期参数匹配。


推荐阅读