【发布时间】:2021-04-17 17:05:35
【问题描述】:
我有一个具体的按钮类:
class ContourButton implements Button {
public icon: string;
public title: string;
constructor(public command: Command) {
}
}
此按钮接受单击后应执行的命令。
命令如下:
export class ContourCommand implements Command {
constructor(public action: EditAction) {}
undo(): void {
this.action.undo();
}
redo(): void {
// TODO
}
execute(): void {
this.action.execute();
}
complete(): void {
this.action.complete();
}
}
这个类提供了一个 reciever 作为 public action: EditAction 包含业务逻辑。
还有一个命令管理器,它将命令添加到堆栈:
class CommandManager {
public currentCommand: Command;
protected commands: Command[] = [];
protected undoCommand: Command;
execute(command: Command): void {
if (command === this.currentCommand) return;
this.currentCommand = command;
this.commands.push(this.currentCommand);
this.currentCommand.execute();
}
}
我不喜欢这行代码:
const command = new ContourCommand(new EditorManager(new Type()));
const button1 = new ContourButton(command);
const button2 = new PinButton(command);
const buttons = [button1, button2];
模板为:
<div *ngFor="let button of buttons" (click)="btnClick($event)"></div>
手柄点击:
public btnClick(button: Button) {
this.commandManager.execute(button.command);
}
因为要创建一个命令,我需要将一个接收者实体指定为new EditorManager(),它具有自己的依赖项。
我是否正确使用了这种模式,以及如何解决这种依赖关系的副作用?我把它写成库,所以我这里没有任何 DI 机制。
【问题讨论】:
-
我完全不明白 ContourButton 为什么要创建一个新命令。它已经需要一个命令作为参数!好像你不喜欢的可以完全删除。
-
抱歉打错字了,我改正了
-
另外你的 CommandManager 类可以被清理。 this.currentCommand 不就是 this.commands 数组中的最后一项吗?如果命令是可撤销的和加倍的(这样当前并不总是最后一个),那么您想知道的信息就是数组中的当前索引。 currentCommand 可以从类似 this.commands[this.currentIndex] 中派生出来。
-
是的,但我需要在课堂上的某处封装命令:[]。这就是 commandManagerExist 的原因。或者你的意思是我不需要变量
currentCommand: Command;? -
ContourCommand 什么都不做?或者您是否删除了逻辑以使其更像是一个最小的示例?它只是包装了一个已经可以执行的 EditAction。所以你可以直接将 EditorManager 传递给 Button。
标签: javascript typescript oop