15.命令模式
命令模式(Command Pattern)的主要目的是把“请求”封装成独立命令对象,以支持排队、记录、撤销和重做
适合使用命令模式的场景
- 调用方只想触发命令,不关心底层执行细节
- 需要支持撤销/重做等历史回退能力
- 需要把操作入队延迟执行或批量执行
- 希望统一记录用户操作日志用于审计或回放
接收者与命令接口
class Editor {
private text = "";
append(content: string): void {
this.text += content;
}
removeLast(length: number): void {
this.text = this.text.slice(0, -length);
}
getText(): string {
return this.text;
}
}
interface Command {
execute(): void;
undo(): void;
}具体命令与调度者
class AppendTextCommand implements Command {
constructor(
private editor: Editor,
private content: string,
) {}
execute(): void {
this.editor.append(this.content);
}
undo(): void {
this.editor.removeLast(this.content.length);
}
}
class CommandManager {
private history: Command[] = [];
run(command: Command): void {
command.execute();
this.history.push(command);
}
undo(): void {
const command = this.history.pop();
command?.undo();
}
}使用示例
const editor = new Editor();
const manager = new CommandManager();
manager.run(new AppendTextCommand(editor, "Hello "));
manager.run(new AppendTextCommand(editor, "World"));
console.log(editor.getText()); // Hello World
manager.undo();
console.log(editor.getText()); // Hello