Intermediate LevelSoftware Engineering Principles
What is the Command Pattern and how does it encapsulate actions for Undo/Redo capabilities?
❓ Interview Prompt: Explain the Command Behavioral Pattern, parameterizing requests as objects, invoker queues, and implementing Undo/Redo operations.
The Command Pattern encapsulates a request or action as an object, allowing clients to parameterize methods with different requests, queue execution, and support undoable operations:
Core Interface:
'Command { execute(): void; undo(): void; }'
Code Implementation Example
typescript
interface Command { execute(): void; undo(): void; }
class TextEditor {
text = '';
}
class AddTextCommand implements Command {
constructor(private editor: TextEditor, private textToAdd: string) {}
execute() { this.editor.text += this.textToAdd; }
undo() { this.editor.text = this.editor.text.slice(0, -this.textToAdd.length); }
}💡Implementing Undo/Redo actions using the Command pattern.
🎯 Interview Key Takeaway
Use the Command pattern to encapsulate requests as objects for job queuing and Undo/Redo capabilities.
#Command#Design Patterns#Undo-Redo#Intermediate
Back to all Software Engineering Principles Questions→