Joseph Haugh
University of New Mexico






public interface Command {
public void execute ();
}
public class LightOnCommand implements Command {
private Light light;
public LightOnCommand (Light light) {
this.light = light;
}
public void execute () {
light.on();
}
}
public class SimpleRemoteControl {
private Command slot;
public SimpleRemoteControl () { }
public void setCommand(Command command) {
slot = command;
}
public void buttonWasPressed() {
slot.execute();
}
}
public class RemoteControlTest {
public static void main(String[] args) {
SimpleRemoteControl remote = new SimpleRemoteControl();
Light light = new Light();
LightOnCommand lightOn = new LightOnCommand(light);
remote.setCommand(lightOn);
remote.buttonWasPressed();
}
}
The Command Pattern encapsulates a request as an object, thereby letting you parameterize other objects with different requests, queue or log requests, and support undo-able operations.

First, we need to expand the Command interface:
public interface Command {
public void execute();
public void undo();
}Now every command must also be undo-able
public class RemoteControl {
private Command[] slots = new Command[10];
private Command recent;
public void setCommand(int index, Command command) {
slot[index] = command;
}
public void buttonWasPressed(int index) {
slot[index].execute();
recent = slot[index];
}
public void undoWasPressed() {
if(recent != null) {
recent.undo();
}
}
}
public class RemoteControl {
private Command[] slots = new Command[10];
private Deque<Command> stack = new LinkedList<>;
public void setCommand(int index, Command command) {
slot[index] = command;
}
public void buttonWasPressed(int index) {
slot[index].execute();
stack.push(slot[index]);
}
public void undoWasPressed() {
if(!stack.isEmpty()) {
Command recent = stack.pop();
recent.undo();
}
}
}
Strategy specifies how something should be done - Merge vs Bubble sort - Probabilistic vs Deterministic primality tests - Doing the same action just in a different way
Command specifies what should be done - Faucet On or Off - Open or Close door - Doing a different action