Design Patterns (GoF) (50 Qs)•Part 2: Behavioral Patterns & Communication (11 - 24)
What is the Command Pattern and how does it enable Undo / Redo?
junior LevelCode ExampleBehavioral
In Simple Words: Encapsulates a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support reversible operations:
- Every command object implements
execute()andundo(). - An Invoker maintains a history stack:
- Running a command: Calls
cmd.execute()and pushes to stack. - Undo: Pops command from stack and calls
cmd.undo()!
- Running a command: Calls
typescript
interface Command {
execute(): void;
undo(): void;
}
class InsertTextCommand implements Command {
constructor(private doc: Document, private text: string) {}
execute() { this.doc.append(this.text); }
undo() { this.doc.deleteLast(this.text.length); }
}