Design patterns
patterns14CommandPattern
- Path
- pkg8patterns/patterns14CommandPattern.java
- Package
- pkg8patterns
- Study order
- 14
- Run
- Single-file source launch
- Command
- java pkg8patterns/patterns14CommandPattern.java
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg8patterns;2 3/*4 * Command (Behavioral)5 * --------------------6 * INTENT: encapsulate a request as an object, allowing queuing, logging, and undo.7 * UML: Command + execute()/undo() ; Invoker triggers; Receiver does the work.8 * PROS: decouples invoker from receiver; supports undo/redo and macros.9 * CONS: many command classes.10 * REAL-WORLD: Runnable, GUI actions, transaction logs, undo stacks.11 */12import java.util.*;13 14public class patterns14CommandPattern {15 16 interface Command { void execute(); void undo(); }17 18 // Receiver19 static class Light {20 private boolean on;21 void on() { on = true; System.out.println("Light ON"); }22 void off() { on = false; System.out.println("Light OFF"); }23 }24 25 static class LightOnCommand implements Command {26 private final Light light;27 LightOnCommand(Light l) { light = l; }28 public void execute() { light.on(); }29 public void undo() { light.off(); }30 }31 32 // Invoker with undo history33 static class RemoteControl {34 private final Deque<Command> history = new ArrayDeque<>();35 void press(Command c) { c.execute(); history.push(c); }36 void undoLast() {37 if (!history.isEmpty()) { System.out.print("undo -> "); history.pop().undo(); }38 }39 }40 41 public static void main(String[] args) {42 RemoteControl remote = new RemoteControl();43 Command lightOn = new LightOnCommand(new Light());44 remote.press(lightOn);45 remote.press(lightOn);46 remote.undoLast();47 remote.undoLast();48 }49}