javascript - 打字稿中的增强抽象方法
问题描述
我有Command
抽象方法“ execute()
”的抽象类。许多其他命令扩展了它。每个都有自己的“ execute()
”实现。
每次执行任何命令时,如何添加一些通用逻辑(如日志记录)?
export abstract class Command {
public abstract execute(...commandParams: any[]): void;
}
解决方案
在我看来,处理这个问题的最好方法是在你调用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
,但参数必须与该特定命令类型的预期参数匹配。
推荐阅读
- c++ - 用于快速排序实现的迭代器与索引
- apache-flink - Flink 从 List 转发文件
文件路径 - azure - 我无法从 Get-AzADUser 中找到足够的属性,是否有任何替代方法可以使用完整的属性?
- python - 从两个列表中查找不同的组合
- firebase - Redux Toolkit:我可以将 createAsycThunk 与 Firebase 侦听器函数一起使用吗(例如 firestore.collection.onSnapshot)
- java - 使用 Java modelMapper 映射 2 个具有不同名称的列表时出现问题
- python - 声音设备库错误
- typescript - 问题:TYPEscript中存在通过cdv文件的ENOENT错误
- python - matplotlib:如何绘制 3d 直方图
- python - 如何在损失函数中建模。预测?(张量流,Keras)