Part 4 of 6 · 2 min read
Undo, macros and queues
What storing commands buys.
The invoker keeps two stacks. done holds commands that have run. undone holds commands that were undone.
class History {
private final Deque<Command> done = new ArrayDeque<>(), undone = new ArrayDeque<>();
void run(Command c) { c.execute(); done.push(c); undone.clear(); }
boolean undo() {
if (done.isEmpty()) return false;
Command c = done.pop(); c.undo(); undone.push(c); return true;
}
boolean redo() {
if (undone.isEmpty()) return false;
Command c = undone.pop(); c.execute(); done.push(c); return true;
}
}
Running a new command clears the redo stack, since the old future no longer applies. A sequence shows how it works. Book 09:00 and 10:00 give [09:00, 10:00]. Undo gives [09:00]. Redo gives [09:00, 10:00] again. Cancel 09:00 gives [10:00]. Undo restores [09:00, 10:00].
A macro command holds a list of commands and runs them as one. GoF calls this a composite command, an instance of the Composite pattern (module 9). Undo runs the parts in reverse order.
class Macro implements Command {
private final List<Command> cmds;
Macro(List<Command> c) { cmds = List.copyOf(c); }
public void execute() { for (Command c : cmds) c.execute(); }
public void undo() { for (int i = cmds.size() - 1; i >= 0; i--) cmds.get(i).undo(); }
}
Running a macro that books 11:00 and 12:00 gives [09:00, 10:00, 11:00, 12:00]. One undo takes both away. The reverse order matters when steps depend on each other.
A queue of commands works because commands are objects. Two booking commands for 14:00 and 15:00 are put in a queue. Nothing happens to the schedule until a worker polls each one and calls execute. This is how job systems and background workers are built: the producer makes commands, and a separate thread runs them (module 4 of Level 5 covers this).
GoF adds a point about persistence. If the command interface also has store and load operations, a log of commands can be written to disk and replayed after a crash.
Macro command
A macro command is a command made of other commands, which runs them in order and undoes them in reverse.
Example: a macro that books 11:00 and 12:00 together.
Check yourself: 1. Why is the redo stack cleared when a new command runs? 2. In what order does a macro undo its parts? 3. What happens to the schedule between queuing a command and polling it?