Command Pattern Fundamentals
What you'll learn: How to turn requests into independent objects that can be passed around, queued, logged, and even undone.
The Core Idea
The Command Pattern encapsulates a request as a self-contained object. Instead of calling a method directly on a receiver, you wrap that call inside a "command object" that knows what to do and who should do it.
Think of it like writing instructions on sticky notes. Instead of shouting "Make coffee!" to your roommate, you write "Make coffee" on a note. Now that note can be:
- Handed to anyone
- Stuck on a queue board
- Paired with a second note saying "Unmake coffee" (undo)
- Logged in a journal for later review
Why Encapsulate Requests?
When you turn requests into objects, you gain powerful capabilities:
Parameterize clients: Different objects can hold different commands and execute them without knowing the details. A button might hold an "Open File" command, while another holds "Save File"—same interface, different actions.
Queue and schedule: Commands in a list can be executed sequentially, in batch, or scheduled for later.
Support undo/redo: Each command object can remember its previous state and provide a reverse operation. Your text editor's undo stack? That's a list of command objects being reversed.
Logging and transactions: By storing command objects, you can replay actions, audit what happened, or roll back a series of operations if something fails.
Key Takeaway:
The Command Pattern decouples the object making a request from the one executing it by wrapping requests as first-class objects, enabling flexible queuing, logging, and undo/redo functionality.