# Purpose
The Command pattern encapsulates a request into an object, allowing methods to be parameterized with different requests, delaying or queuing executions, and supporting undo.
In simple terms: we create an object with the necessary information for a handler to perform the task.
# Problem
-
Coupling: When the sender (e.g. a button) is directly tied to the business logic.
-
Reusability: Difficulty in adding new requests without modifying existing classes.
# Solution
-
Command Objects: Encapsulation of all the information necessary for the action.
-
Separation: Senders don't know the execution details.
# Structure
# Participants
- Command: Interface with the execute() method.
- ConcreteCommand: Implements Command and invokes the Receiver.
- Invoker: Maintains a reference to the command and calls execute().
- Receiver: Performs the actual work (business logic).
- Client: Creates and configures commands and receivers.
# When to Use It
-
Parameterize objects according to an action to be performed.
-
Implement undo and redo operations.
-
Maintain a history of requests.
# Advantages
-
verified
Decoupling: Isolates the invocation from the execution.
-
verified
Extensibility: New commands without changing base code.
-
verified
Flexibility: Supports complex queues and histories.
# Disadvantages
-
warning
Complexity: More classes and objects in the system.
-
warning
Overhead: Simple actions turned into commands.
# Example: Smart Home
Control of lights, thermostats, and security through a centralized interface. The commands encapsulate the on/off actions.
# Java Code
interface Command { void execute(); }
class LightOnCommand implements Command {
private Light light;
public void execute() { light.turnOn(); }
}
class RemoteControl {
private Command command;
public void setCommand(Command c) { command = c; }
public void pressButton() { command.execute(); }
}
# Mapping Participants
- Command (Interface): The execute() contract.
- LightOn/Off (ConcreteCommand): Specific logic.
- Light (Receiver): Business logic.
- RemoteControl (Invoker): Initiates the action.
# Conclusions
It makes it easier to extend to include more devices while keeping loose coupling between sender and receiver.
# Related Patterns
Memento
Maintains the previous state for undo operations.
Composite
Composite structures for complex macro-commands.