Behavioral PatternsCommand PatternEasy⏱️ ~2 min

Command Pattern: Definition & Core Concept

Definition
Command Pattern encapsulates a request as an object, allowing you to parameterize clients with different requests, queue or log requests, and support undoable operations.

The Command Pattern turns requests into standalone objects that contain all information about the request. This transformation lets you pass requests as method arguments, delay or queue request execution, and implement reversible operations.

Core Problem Solved

Without Command Pattern, application logic becomes tightly coupled to UI elements. A Button directly calls document.save(), making it impossible to reuse the save logic elsewhere, create keyboard shortcuts, implement undo functionality, or queue operations. The pattern solves this by decoupling the object that invokes the operation from the one that performs it.

When You Need It

First, you need undo/redo functionality where operations must be reversible. Second, you want to queue operations for later execution or log them for audit trails. Third, you have multiple UI elements (buttons, menu items, keyboard shortcuts) that trigger the same operation. Fourth, you need to implement macro recording where complex sequences of actions can be saved and replayed. If none of these apply, direct method calls are simpler and appropriate instead.

Interview Tip: Emphasize that Command Pattern is about turning "doing something" into "an object that represents doing something." This seemingly simple change unlocks undo, queuing, and macro functionality.
💡 Key Takeaways
Encapsulates requests as objects containing all request information
Decouples invoker (button, menu) from receiver (actual business logic)
Enables undo/redo by storing state before execution
Supports queuing, logging, and macro recording of operations
Each command knows its receiver and can execute/undo itself
📌 Examples
1Text editor with undo/redo for formatting commands
2Drawing application where each shape addition is a command
3Task management system queuing background operations
← Back to Command Pattern Overview
Command Pattern: Definition & Core Concept | Command Pattern - System Overflow