Middle+
Do you use the Command pattern in your work?
sobes.tech AI
Answer from AI
Yes, I use the Command pattern.
It is useful for:
- Encapsulating a request as an object, allowing it to be passed as a parameter, queued, or logged.
- Supporting undo and redo operations.
- Organizing request handling in graphical user interfaces, transactions, and logging systems.
A simple implementation:
// Command interface
interface Command {
void execute();
}
// Concrete command
class LightOnCommand implements Command {
private Light light;
public LightOnCommand(Light light) {
this.light = light;
}
@Override
public void execute() {
light.on();
}
}
// Receiver
class Light {
public void on() {
System.out.println("Light is ON");
}
public void off() {
System.out.println("Light is OFF");
}
}
// Invoker
class RemoteControl {
private Command command;
public void setCommand(Command command) {
this.command = command;
}
public void pressButton() {
command.execute();
}
}
// Client
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(); // Light is ON
}
}
A real-world example from my experience:
In a project managing orders, I used the Command pattern to implement "Cancel Order" and "Reorder" functions. Each operation was encapsulated in a separate command object, which could be easily queued for asynchronous processing or saved for later cancellation.