CSE Roadmap

Core tier · about 3 hours · 6 parts

Part 3 of 6 · 2 min read

The parts

Command, receiver, invoker.

GoF names four roles. The Command declares an interface with execute. A ConcreteCommand binds a receiver to an action. The Receiver knows how to do the real work. The Invoker asks the command to run. The Client creates the concrete command and gives it its receiver.

Here the receiver is a day schedule. The commands are booking and cancelling a slot.

class Schedule {
    private final Set<String> booked = new TreeSet<>();
    boolean add(String slot)    { return booked.add(slot); }
    boolean remove(String slot) { return booked.remove(slot); }
    public String toString()    { return booked.toString(); }
}

interface Command { void execute(); void undo(); }

class Book implements Command {
    private final Schedule s; private final String slot; private boolean did;
    Book(Schedule s, String slot) { this.s = s; this.slot = slot; }
    public void execute() { did = s.add(slot); }
    public void undo()    { if (did) s.remove(slot); }
}

class Cancel implements Command {
    private final Schedule s; private final String slot; private boolean did;
    Cancel(Schedule s, String slot) { this.s = s; this.slot = slot; }
    public void execute() { did = s.remove(slot); }
    public void undo()    { if (did) s.add(slot); }
}

The did flag matters. execute records whether it really changed anything. If a slot was already booked when Book ran, then add returned false, and undo must not remove a booking that this command did not make. A test confirms it: after booking 09:00 twice, undoing the second leaves the first in place.

This matches GoF's advice that execute should store the state needed to reverse itself. Some commands store more, such as the old value of a field. Here one boolean is enough.

Check yourself: 1. Which class is the receiver? 2. Why does undo check did? 3. Who is the client in this example?