Encapsulate a request as an object, enabling undo/redo, queuing, and logging of operations.
Turns a request into a stand-alone object containing all information about the request. Decouples the object that invokes the operation from the one that performs it.
execute() / undo())Command interface with execute() (and optionally undo())Invoker that stores and triggers commandsinterface Command { execute(): void; undo(): void; }
class TextEditor {
private text = '';
insert(s: string) { this.text += s; }
delete(n: number) { this.text = this.text.slice(0, -n); }
getText() { return this.text; }
}
class InsertCommand implements Command {
constructor(private editor: TextEditor, private text: string) {}
execute() { this.editor.insert(this.text); }
undo() { this.editor.delete(this.text.length); }
}
class CommandHistory {
private history: Command[] = [];
execute(cmd: Command) { cmd.execute(); this.history.push(cmd); }
undo() { this.history.pop()?.undo(); }
}
const editor = new TextEditor();
const history = new CommandHistory();
history.execute(new InsertCommand(editor, 'Hello'));
history.execute(new InsertCommand(editor, ' World'));
history.undo(); // removes ' World'