Skip to main content
InterviewHubPRO
Section Overview
Q11

Question 11 of 50

Part 2: Behavioral Patterns & Communication (11 - 24)

22%
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() and undo().
  • 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()!
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); }
}