Thanksgiving Sale: Use Coupon Code THANKS25 to Get Extra 25% Off.
The Command Pattern is a behavioral design pattern that encapsulates a request as an object, thereby allowing for parameterization of clients with queues, requests, and operations. This pattern is particularly useful in scenarios where you need to decouple the sender of a request from its receiver, enabling more flexible and maintainable code.
Command Interface: This defines a method for executing a command. All concrete commands will implement this interface.
public interface Command {
void execute();
}
Concrete Command: This class implements the Command interface and defines the binding between a receiver and an action. It invokes the corresponding operation on the receiver.
public class LightOnCommand implements Command {
private Light light;
public LightOnCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.turnOn();
}
}
Receiver: This is the class that knows how to perform the operations associated with the command. It contains the business logic.
public class Light {
public void turnOn() {
System.out.println("Light is ON");
}
}
Invoker: This class is responsible for invoking the command. It holds a command and can execute it.
public class RemoteControl {
private Command command;
public void setCommand(Command command) {
this.command = command;
}
public void pressButton() {
command.execute();
}
}
Client: The client creates a command object and associates it with a receiver. It then passes the command to the invoker.
public class Client {
public static void main(String[] args) {
Light light = new Light();
Command lightOn = new LightOnCommand(light);
RemoteControl remote = new RemoteControl();
remote.setCommand(lightOn);
remote.pressButton(); // Output: Light is ON
}
}
The Command Pattern is a powerful tool in Object-Oriented Design that enhances the flexibility and maintainability of your code. By encapsulating actions as objects, it allows for a clean separation of concerns, making your software easier to manage and extend. Understanding this pattern is essential for software engineers and data scientists preparing for technical interviews, as it demonstrates a solid grasp of design principles.