Command Pattern: Encapsulating Requests
You'll learn: How to turn requests or operations into independent objects that can be stored, passed around, and manipulated like data.
The Core Idea
The Command Pattern wraps a request (like "save file" or "turn on light") into a standalone object that contains all the information needed to perform that action. Instead of calling a method directly, you create a command object that knows how to execute that method.
Think of a restaurant: instead of shouting your order to the chef, you write it on a slip of paper. That slip can be queued with other orders, handed to different servers, posted on a board for tracking, or even torn up if you change your mind. The written order is a command object—it encapsulates your request independently.
Why Encapsulate Requests?
When requests are objects, powerful capabilities emerge:
- Queuing: Commands can wait in line (task scheduler, job queue)
- Logging: Store commands to replay later or audit what happened
- Undo/Redo: Keep executed commands in a stack; reverse them on demand
- Remote execution: Send command objects across networks
- Macro recording: Combine multiple commands into one composite command
Structure
A command typically has:
- An
execute()method that performs the action - References to the receiver (the object that does the real work)
- Parameters needed for the operation
The invoker (like a button or menu) knows nothing about what the command does—it just calls execute().
Key Takeaway: The Command Pattern transforms actions into first-class objects, enabling queuing, logging, undo functionality, and decoupling the requester from the performer.