Command Design Pattern in Java
The Command design pattern is a behavioral design pattern that encapsulates a request or an action as a separate object, allowing for more flexibility and extensibility in handling requests.
What is the Command Design Pattern?
The Command pattern is used to decouple the requester of an action from the provider of the action. It does this by introducing an intermediate object, known as the Command, which encapsulates the request.
Components of the Command Pattern
- Command: This is the interface that declares the execute method.
- ConcreteCommand: This class implements the Command interface and defines the actions to be performed.
- Receiver: This is the object that actually performs the action.
- Invoker: This is the object that receives the command and invokes the execute method.
- Client: This is the object that creates the command and sets the receiver.
Java Implementation
Here's an example implementation of the Command pattern in Java:
Java
// Command interface
public interface Command {
void execute();
}
// Receiver class
public class Light {
public void turnOn() {
System.out.println("Light is on");
}
public void turnOff() {
System.out.println("Light is off");
}
}
// ConcreteCommand classes
public class TurnOnCommand implements Command {
private Light light;
public TurnOnCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.turnOn();
}
}
public class TurnOffCommand implements Command {
private Light light;
public TurnOffCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.turnOff();
}
}
// Invoker class
public class RemoteControl {
private Command command;
public void setCommand(Command command) {
this.command = command;
}
public void pressButton() {
command.execute();
}
}
// Client code
public class Main {
public static void main(String[] args) {
Light light = new Light();
Command turnOn = new TurnOnCommand(light);
Command turnOff = new TurnOffCommand(light);
RemoteControl remote = new RemoteControl();
remote.setCommand(turnOn);
remote.pressButton(); // Output: Light is on
remote.setCommand(turnOff);
remote.pressButton(); // Output: Light is off
}
}Benefits of the Command Pattern
- Decouples the requester from the provider
- Allows for extensibility and flexibility
- Supports undo and redo operations
- Improves code reusability
Real-World Applications
- Remote control systems
- GUI buttons and menu items
- Transactional systems (e.g., banking, e-commerce)
Conclusion
The Command design pattern is a powerful tool for encapsulating requests and actions, allowing for more flexibility and extensibility in handling requests. By using the Command pattern, you can decouple the requester from the provider, improve code reusability, and support undo and redo operations.
Comments
Post a Comment