Command Design Pattern in Java
Command turns a request into an object. Because it is an object, you can store it, pass it around, delay it or undo it.
Real life example
In a restaurant, the waiter writes your order on paper. The paper (command) goes to the chef.
When to use
You need buttons, menus, queues, or undo and redo.
Complete Java example
Save this as Main.java, then run javac Main.java and java Main.
public class Main {
public static void main(String[] args) {
Light light = new Light();
RemoteControl remote = new RemoteControl();
remote.setCommand(new LightOn(light));
remote.press(); // Light ON
}
}
interface Command { void execute(); }
class Light {
void on() { System.out.println("Light ON"); }
void off() { System.out.println("Light OFF"); }
}
class LightOn implements Command {
private Light light;
LightOn(Light l) { light = l; }
public void execute() { light.on(); }
}
class LightOff implements Command {
private Light light;
LightOff(Light l) { light = l; }
public void execute() { light.off(); }
}
class RemoteControl { // does not know what the command does
private Command command;
void setCommand(Command c) { command = c; }
void press() { command.execute(); }
}Output
Light ON