Skip to lesson

Command: actions as objects, with undo

ShopLite's cart needs an Undo button, and the app must replay the shopper's actions after the connection drops. How do you undo something that was only a method call?

Command interface with execute() and undo()

Command is an object that holds everything needed to perform one action: which object to act on and with which values. Its interface is small: execute() does the action and undo() reverses it.

ShopLite's cart gets an Undo button. Below, adding pen sets becomes an object with execute() and undo().

Example 1 · The smallest command: add an item, then undo it

FirstCommandDemo.javaJava
import java.util.LinkedHashMap;import java.util.Map;
class Cart {                                              // the receiver: does the real work    private final Map<String, Integer> items = new LinkedHashMap<>();    private String coupon;
    void add(String sku, int qty) {        items.merge(sku, qty, Integer::sum);    }
    void reduce(String sku, int qty) {        int left = items.getOrDefault(sku, 0) - qty;        if (left > 0) {            items.put(sku, left);        } else {            items.remove(sku);        }    }
    int removeAll(String sku) {                           // returns how many were removed        Integer qty = items.remove(sku);        return qty == null ? 0 : qty;    }
    String coupon() { return coupon; }    void setCoupon(String coupon) { this.coupon = coupon; }
    @Override    public String toString() {        return items + (coupon == null ? "" : " coupon=" + coupon);    }}
interface Command {    void execute();    void undo();}
class AddItemCommand implements Command {    private final Cart cart;    private final String sku;    private final int qty;
    AddItemCommand(Cart cart, String sku, int qty) {        this.cart = cart;        this.sku = sku;        this.qty = qty;    }
    public void execute() { cart.add(sku, qty); }    public void undo() { cart.reduce(sku, qty); }}
public class FirstCommandDemo {    public static void main(String[] args) {        Cart cart = new Cart();        cart.add("EAR-01", 1);
        Command addPens = new AddItemCommand(cart, "PEN-02", 2);   // the action, not yet done        System.out.println("Before:  " + cart);        addPens.execute();        System.out.println("Execute: " + cart);        addPens.undo();        System.out.println("Undo:    " + cart);    }}
Output
Before:  {EAR-01=1}
Execute: {EAR-01=1, PEN-02=2}
Undo:    {EAR-01=1}

What this code does

  • Creating addPens does nothing to the cart yet. The action happens only when execute() is called, and the object remembers enough to reverse it.
  • The cart is the receiver: the command only calls its add and reduce methods with the stored values.

Four roles work together. The receiver (Cart) does the real work, the command wraps one request to it, the invoker (a button or a history manager) runs commands without knowing what they do, and the client creates the commands and hands them over.

Cart commands: AddItem, RemoveItem, ApplyCoupon

Receiver is the object that does the real work for a command, here the Cart. The command only calls the receiver's methods with the values it stored.

Each cart action becomes one class. Removing an item or applying a coupon needs the old state to undo, so execute() saves it first.

Example 2 · RemoveItem and ApplyCoupon save the old state

CartCommandsDemo.javaJava
import java.util.LinkedHashMap;import java.util.Map;
class Cart {    private final Map<String, Integer> items = new LinkedHashMap<>();    private String coupon;
    void add(String sku, int qty) {        items.merge(sku, qty, Integer::sum);    }
    void reduce(String sku, int qty) {        int left = items.getOrDefault(sku, 0) - qty;        if (left > 0) {            items.put(sku, left);        } else {            items.remove(sku);        }    }
    int removeAll(String sku) {                           // returns how many were removed        Integer qty = items.remove(sku);        return qty == null ? 0 : qty;    }
    String coupon() { return coupon; }    void setCoupon(String coupon) { this.coupon = coupon; }
    @Override    public String toString() {        return items + (coupon == null ? "" : " coupon=" + coupon);    }}interface Command {    void execute();    void undo();    String describe();}
class AddItemCommand implements Command {    private final Cart cart;    private final String sku;    private final int qty;
    AddItemCommand(Cart cart, String sku, int qty) {        this.cart = cart;        this.sku = sku;        this.qty = qty;    }
    public void execute() { cart.add(sku, qty); }    public void undo() { cart.reduce(sku, qty); }    public String describe() { return "add " + qty + " x " + sku; }}
class RemoveItemCommand implements Command {    private final Cart cart;    private final String sku;    private int removedQty;                               // old state, saved by execute
    RemoveItemCommand(Cart cart, String sku) {        this.cart = cart;        this.sku = sku;    }
    public void execute() { removedQty = cart.removeAll(sku); }    public void undo() { if (removedQty > 0) cart.add(sku, removedQty); }    public String describe() { return "remove " + sku; }}
class ApplyCouponCommand implements Command {    private final Cart cart;    private final String code;    private String previous;                              // old coupon, saved by execute
    ApplyCouponCommand(Cart cart, String code) {        this.cart = cart;        this.code = code;    }
    public void execute() {        previous = cart.coupon();        cart.setCoupon(code);    }
    public void undo() { cart.setCoupon(previous); }    public String describe() { return "apply coupon " + code; }}
public class CartCommandsDemo {    public static void main(String[] args) {        Cart cart = new Cart();        cart.add("EAR-01", 1);        cart.add("PEN-02", 3);        cart.setCoupon("WELCOME");        System.out.println("Start:  " + cart);
        Command remove = new RemoveItemCommand(cart, "PEN-02");        Command coupon = new ApplyCouponCommand(cart, "FEST10");        remove.execute();        coupon.execute();        System.out.println("After:  " + cart);
        coupon.undo();        System.out.println("Undo 1: " + cart);        remove.undo();        System.out.println("Undo 2: " + cart);    }}
Output
Start:  {EAR-01=1, PEN-02=3} coupon=WELCOME
After:  {EAR-01=1} coupon=FEST10
Undo 1: {EAR-01=1} coupon=WELCOME
Undo 2: {EAR-01=1, PEN-02=3} coupon=WELCOME

What this code does

  • RemoveItemCommand stores the 3 pen sets it removed, so undo puts back 3, not 1. ApplyCouponCommand stores WELCOME before replacing it, so undo restores it instead of leaving no coupon.
  • The undone pen sets come back at the end of the cart's order, because the map adds them again. The quantities and coupon match the start exactly.

AddItemCommand undoes by reducing the quantity again. RemoveItemCommand and ApplyCouponCommand are harder: to undo them you need the quantity that was in the cart, or the coupon that was applied before.

The rule: execute() saves whatever undo() will need, before it changes anything. A command that forgets this can do its job but cannot take it back.

Find the bug

Spot the undo bug

Each snippet has one wrong line. Tap it, then read the fix.

Undo should bring back the earlier coupon.

Round 1 of 2
Common mistake: undoing a coupon by setting it to null. The shopper's earlier coupon is lost, so save the old value.

An invoker with history stacks for undo and redo

Undo / redo stack is the pair of stacks an invoker keeps. Every command it runs goes on the undo stack, an undone command moves to the redo stack, and running a new command clears the redo stack.

The invoker keeps two stacks. undo() pops the latest command and redo() brings it back. Below, CartHistory is the invoker.

Example 3 · CartHistory: undo and redo with two stacks

UndoRedoDemo.javaJava
import java.util.ArrayDeque;import java.util.Deque;
import java.util.LinkedHashMap;import java.util.Map;
class Cart {    private final Map<String, Integer> items = new LinkedHashMap<>();    private String coupon;
    void add(String sku, int qty) {        items.merge(sku, qty, Integer::sum);    }
    void reduce(String sku, int qty) {        int left = items.getOrDefault(sku, 0) - qty;        if (left > 0) {            items.put(sku, left);        } else {            items.remove(sku);        }    }
    int removeAll(String sku) {        Integer qty = items.remove(sku);        return qty == null ? 0 : qty;    }
    String coupon() { return coupon; }    void setCoupon(String coupon) { this.coupon = coupon; }
    @Override    public String toString() {        return items + (coupon == null ? "" : " coupon=" + coupon);    }}interface Command {    void execute();    void undo();    String describe();}
class AddItemCommand implements Command {    private final Cart cart;    private final String sku;    private final int qty;
    AddItemCommand(Cart cart, String sku, int qty) {        this.cart = cart;        this.sku = sku;        this.qty = qty;    }
    public void execute() { cart.add(sku, qty); }    public void undo() { cart.reduce(sku, qty); }    public String describe() { return "add " + qty + " x " + sku; }}
class RemoveItemCommand implements Command {    private final Cart cart;    private final String sku;    private int removedQty;
    RemoveItemCommand(Cart cart, String sku) {        this.cart = cart;        this.sku = sku;    }
    public void execute() { removedQty = cart.removeAll(sku); }    public void undo() { if (removedQty > 0) cart.add(sku, removedQty); }    public String describe() { return "remove " + sku; }}
class ApplyCouponCommand implements Command {    private final Cart cart;    private final String code;    private String previous;                              // old coupon, saved by execute
    ApplyCouponCommand(Cart cart, String code) {        this.cart = cart;        this.code = code;    }
    public void execute() {        previous = cart.coupon();        cart.setCoupon(code);    }
    public void undo() { cart.setCoupon(previous); }    public String describe() { return "apply coupon " + code; }}
class CartHistory {                                        // the invoker    private final Deque<Command> undoStack = new ArrayDeque<>();    private final Deque<Command> redoStack = new ArrayDeque<>();
    void run(Command command) {        command.execute();        undoStack.push(command);        redoStack.clear();                                 // a new action ends the old future    }
    String undo() {        if (undoStack.isEmpty()) return "nothing to undo";        Command command = undoStack.pop();        command.undo();        redoStack.push(command);        return "undid " + command.describe();    }
    String redo() {        if (redoStack.isEmpty()) return "nothing to redo";        Command command = redoStack.pop();        command.execute();        undoStack.push(command);        return "redid " + command.describe();    }}
public class UndoRedoDemo {    public static void main(String[] args) {        Cart cart = new Cart();        CartHistory history = new CartHistory();
        history.run(new AddItemCommand(cart, "EAR-01", 1));        history.run(new AddItemCommand(cart, "PEN-02", 2));        history.run(new ApplyCouponCommand(cart, "FEST10"));        System.out.println("Cart: " + cart);
        System.out.println(history.undo() + " -> " + cart);        System.out.println(history.undo() + " -> " + cart);        System.out.println(history.redo() + " -> " + cart);
        history.run(new AddItemCommand(cart, "MUG-03", 1));        System.out.println("New action -> " + cart);        System.out.println(history.redo());    }}
Output
Cart: {EAR-01=1, PEN-02=2} coupon=FEST10
undid apply coupon FEST10 -> {EAR-01=1, PEN-02=2}
undid add 2 x PEN-02 -> {EAR-01=1}
redid add 2 x PEN-02 -> {EAR-01=1, PEN-02=2}
New action -> {EAR-01=1, PEN-02=2, MUG-03=1}
nothing to redo

What this code does

  • Two undos take back the coupon and then the pens, newest first. One redo re-runs the pens command, because it is on top of the redo stack.
  • Adding the mug clears the redo stack, so the coupon can no longer be redone: the history branched.

This is exactly how Ctrl+Z and Ctrl+Y behave in an editor. Running a brand-new command clears the redo stack, because the old future no longer makes sense.

Use ArrayDeque for the stacks; the old Stack class is slower and kept only for compatibility.

Predict the output

Predict the two stacks

Read the code, then pick what it prints. The top of each stack is on the left.

Three commands run, two are undone and one is redone.

import java.util.ArrayDeque;
import java.util.Deque;
public class Demo {
public static void main(String[] args) {
Deque<String> undo = new ArrayDeque<>();
Deque<String> redo = new ArrayDeque<>();
undo.push("A");
undo.push("B");
undo.push("C");
redo.push(undo.pop());
redo.push(undo.pop());
undo.push(redo.pop());
System.out.println(undo + " " + redo);
}
}

Queuing and logging commands for later

Invoker is the object that runs commands without knowing what they do, such as a button, a history manager, a queue or an ExecutorService. It depends only on the command interface.

Because a command is a plain object, it can wait. Below, cart actions are queued while offline, then replayed and logged.

Example 4 · Queue cart actions offline, then replay and log them

QueueAndLogDemo.javaJava
import java.util.ArrayDeque;import java.util.ArrayList;import java.util.List;import java.util.Queue;
import java.util.LinkedHashMap;import java.util.Map;
class Cart {    private final Map<String, Integer> items = new LinkedHashMap<>();    private String coupon;
    void add(String sku, int qty) {        items.merge(sku, qty, Integer::sum);    }
    void reduce(String sku, int qty) {        int left = items.getOrDefault(sku, 0) - qty;        if (left > 0) {            items.put(sku, left);        } else {            items.remove(sku);        }    }
    int removeAll(String sku) {        Integer qty = items.remove(sku);        return qty == null ? 0 : qty;    }
    String coupon() { return coupon; }    void setCoupon(String coupon) { this.coupon = coupon; }
    @Override    public String toString() {        return items + (coupon == null ? "" : " coupon=" + coupon);    }}interface Command {    void execute();    void undo();    String describe();}
class AddItemCommand implements Command {    private final Cart cart;    private final String sku;    private final int qty;
    AddItemCommand(Cart cart, String sku, int qty) {        this.cart = cart;        this.sku = sku;        this.qty = qty;    }
    public void execute() { cart.add(sku, qty); }    public void undo() { cart.reduce(sku, qty); }    public String describe() { return "add " + qty + " x " + sku; }}
class RemoveItemCommand implements Command {    private final Cart cart;    private final String sku;    private int removedQty;
    RemoveItemCommand(Cart cart, String sku) {        this.cart = cart;        this.sku = sku;    }
    public void execute() { removedQty = cart.removeAll(sku); }    public void undo() { if (removedQty > 0) cart.add(sku, removedQty); }    public String describe() { return "remove " + sku; }}
class ApplyCouponCommand implements Command {    private final Cart cart;    private final String code;    private String previous;                              // old coupon, saved by execute
    ApplyCouponCommand(Cart cart, String code) {        this.cart = cart;        this.code = code;    }
    public void execute() {        previous = cart.coupon();        cart.setCoupon(code);    }
    public void undo() { cart.setCoupon(previous); }    public String describe() { return "apply coupon " + code; }}
public class QueueAndLogDemo {    public static void main(String[] args) {        Cart cart = new Cart();        Queue<Command> pending = new ArrayDeque<>();           // network is down        List<String> auditLog = new ArrayList<>();
        pending.add(new AddItemCommand(cart, "EAR-01", 1));        pending.add(new AddItemCommand(cart, "PEN-02", 2));        pending.add(new ApplyCouponCommand(cart, "FEST10"));        pending.add(new RemoveItemCommand(cart, "EAR-01"));        System.out.println("Offline: " + pending.size() + " actions queued, cart " + cart);
        while (!pending.isEmpty()) {                            // network is back: replay in order            Command command = pending.poll();            command.execute();            auditLog.add(command.describe());        }        System.out.println("Online:  cart " + cart);        System.out.println("Audit log:");        for (int i = 0; i < auditLog.size(); i++) {            System.out.println("  " + (i + 1) + ". " + auditLog.get(i));        }    }}
Output
Offline: 4 actions queued, cart {}
Online:  cart {PEN-02=2} coupon=FEST10
Audit log:
  1. add 1 x EAR-01
  2. add 2 x PEN-02
  3. apply coupon FEST10
  4. remove EAR-01

What this code does

  • While offline, the actions are only stored: the cart stays empty. When the network returns, the queue is replayed in the same order the shopper acted.
  • Each command describes itself, so the audit log needs no knowledge of the command classes.

A mobile app that loses its network can queue the shopper's actions and replay them in order when it reconnects. A scheduler can hold "start the flash sale" until 8 pm.

Commands can also describe themselves, so every action can be written to an audit log. If the log keeps enough detail, replaying it from an empty cart rebuilds the same cart, which helps with debugging and recovery.

Order of execution

Replay after offline

Put the steps in the order they happen.

Runnable as the simplest command in the JDK

Runnable is the JDK's command interface. Below, lambdas are commands for a list and for an ExecutorService.

Example 5 · Runnable: commands for a list and for an executor

RunnableCommandsDemo.javaJava
import java.util.List;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;
public class RunnableCommandsDemo {    static void remind(String phone) {        System.out.println("  reminder: items left in cart, " + phone);    }
    public static void main(String[] args) throws InterruptedException {        List<Runnable> nightlyJobs = List.of(                () -> System.out.println("  report: 42 orders today"),                () -> remind("9811100001"),                () -> System.out.println("  cache: product list refreshed"));
        System.out.println("Run now, in this thread:");        for (Runnable job : nightlyJobs) {            job.run();        }
        System.out.println("Run later, on a worker thread:");        ExecutorService worker = Executors.newSingleThreadExecutor();   // the invoker        for (Runnable job : nightlyJobs) {            worker.submit(job);        }        worker.shutdown();        worker.awaitTermination(5, TimeUnit.SECONDS);        System.out.println("All jobs done");    }}
Output
Run now, in this thread:
  report: 42 orders today
  reminder: items left in cart, 9811100001
  cache: product list refreshed
Run later, on a worker thread:
  report: 42 orders today
  reminder: items left in cart, 9811100001
  cache: product list refreshed
All jobs done

What this code does

  • Each lambda is a Runnable command: it packs an action to run later. The list and the executor never know what the jobs do.
  • A single-thread executor runs the submitted commands one by one, in order. awaitTermination waits for them, so All jobs done prints last.

Runnable has one method, run(), and no undo. The code that holds it, a list, a Thread or an ExecutorService, decides when it runs. The executor is an invoker: you submit commands and its worker threads execute them later. Callable is the variant that returns a result.

A macro command is a command that holds other commands: its execute() runs them in order and its undo() undoes them in reverse, so a "Buy the study kit" button is one step in the history.

Next step

Check your understanding

12 quick questions