Command Design Pattern
What is the Command Design Pattern?
The Command Design Pattern is a behavioral design pattern. It is used to turn a request into a separate object called a command. This allows you to store, pass, and execute requests at a later time.
In simple words, this pattern helps you decouple (separate) the object that sends a request from the object that performs the action.
Real-Life Example
Think about a TV remote:
- You press the ON button
- The remote does not know how the TV works internally
- It just sends a command to turn the TV ON
Here, the remote is the Invoker, the button action is the Command, and the TV is the Receiver.
Key Components of Command Pattern
- Command – An interface that declares an execute method
- Concrete Command – Implements the command and calls the receiver
- Receiver – The actual object that performs the action
- Invoker – Triggers the command
- Client – Creates and configures the command
Java Example of Command Design Pattern
Step 1: Create Command Interface
interface Command {
void execute();
}
Step 2: Create Receiver Class
class Light {
public void turnOn() {
System.out.println("Light is ON");
}
public void turnOff() {
System.out.println("Light is OFF");
}
}
Step 3: Create Concrete Command Classes
class LightOnCommand implements Command {
private Light light;
public LightOnCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.turnOn();
}
}
class LightOffCommand implements Command {
private Light light;
public LightOffCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.turnOff();
}
}
Step 4: Create Invoker Class
class RemoteControl {
private Command command;
public void setCommand(Command command) {
this.command = command;
}
public void pressButton() {
command.execute();
}
}
Step 5: Client Code
public class CommandPatternDemo {
public static void main(String[] args) {
Light livingRoomLight = new Light();
Command lightOn = new LightOnCommand(livingRoomLight);
Command lightOff = new LightOffCommand(livingRoomLight);
RemoteControl remote = new RemoteControl();
remote.setCommand(lightOn);
remote.pressButton();
remote.setCommand(lightOff);
remote.pressButton();
}
}
Output
Light is ON Light is OFF
Advantages of Command Design Pattern
- Loose coupling between sender and receiver
- Easy to add new commands without changing existing code
- Supports undo/redo operations
- Improves code maintainability
When to Use Command Pattern?
- When you want to parameterize objects with actions
- When you need to queue or log requests
- When you want to implement undo/redo functionality
Conclusion
The Command Design Pattern is very useful when you want to separate the request from the execution logic. It makes your code more flexible, clean, and easy to extend, especially in large Java applications.
Was this tutorial helpful?