The Command pattern is a behavioral design pattern that converts requests or simple operations into objects. These objects encapsulate the request or operation, allowing you to delay or queue requests, undo/redo actions, and support various forms of program execution. In essence, the Command pattern facilitates the separation of concerns by decoupling the sender and receiver of a command.
The Command pattern has four main components:
1. Command Interface: Declares the method(s) for executing the command.
2. Concrete Command Implementations: Provides the implementation for the Command Interface.
3. Invoker: Takes a command object and is responsible for executing it.
4. Receiver: Performs the actual business logic associated with the command.
Here is an example of the Command pattern implemented in Java:
// Command Interface
public interface Command {
void execute();
}
// Concrete Command Implementation
public class ConcreteCommand implements Command {
private Receiver receiver;
public ConcreteCommand(Receiver recv) {
this.receiver = recv;
}
@Override
public void execute() {
receiver.action();
}
}
// Receiver
public class Receiver {
public void action() {
System.out.println("Performing action");
}
}
// Invoker
public class Invoker {
private Command command;
public void setCommand(Command cmd) {
this.command = cmd;
}
public void executeCommand() {
command.execute();
}
}
// Client
public class Client {
public static void main(String[] args) {
Receiver receiver = new Receiver();
Command concreteCommand = new ConcreteCommand(receiver);
Invoker invoker = new Invoker();
invoker.setCommand(concreteCommand);
invoker.executeCommand(); // Outputs "Performing action"
}
}
Benefits of the Command pattern:
1. Decouples the sender and receiver of a command, allowing for greater flexibility of requests and operations.
2. Enables the creation of undo/redo functionality by recording a history of commands and reversing their effects.
3. Provides a framework for extensibility and maintainability by allowing for the addition of new commands without affecting the object being acted upon.
4. Supports the construction of complex command hierarchies and composite commands.