00:00

Command Design Pattern in Java

Last updated:

The command design pattern in Java turns a request, such as "add this item to the cart" or "transfer 30,000 to savings", into an object. Because the request is now an object, it can be stored, queued, logged, executed later, undone or retried, and the code that triggers it no longer needs to know how it is carried out.

It matters because plain method calls disappear the moment they finish. Undo, audit trails, scheduled jobs and multi-step rollbacks all need a record of what was asked. The Command pattern gives you that record. It is a behavioral design pattern, and every Java developer already uses it when passing a Runnable to an ExecutorService.

1. What Is the Command Design Pattern?

The GoF intent is: "Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations."

A command object bundles three things: what to do (its class), on which object (the receiver it holds) and with which data (its fields). It exposes a uniform method, usually execute(), and often undo().

An invoker, such as a history manager, a queue or a scheduler, triggers commands without knowing what each one does. That separation is the key: the object that decides when something happens is decoupled from the object that knows how to do it. New operations are new command classes, and the invoker never changes (Open/Closed Principle).

2. Key Components

ComponentResponsibilityIn the Basic Example
CommandInterface with execute() and, optionally, undo()CartCommand
Concrete CommandHolds the receiver and the data, and calls the receiverAddItem, RemoveItem, ApplyCoupon
ReceiverThe object that does the real workCart
InvokerRuns commands and may store them for undo, retry or auditCartHistory
ClientCreates commands, wires them to receivers, and hands them to the invokermain

The client creates a command with its receiver and data, and gives it to the invoker. The invoker calls execute() and records the command. Later it can call undo() on the same object, which reverses the change on the same receiver.

3. When Is Command Useful?

  • Undo and redo: a shopping cart where shoppers can reverse their last actions.
  • Deferred and queued work: month-end bank instructions stored now and executed by a worker later.
  • Multi-step operations with rollback: placing an order across stock, payment and shipping, undoing completed steps if one fails.

4. UML Class Diagram

The diagram shows the Basic Example.

Command UML class diagram CartHistory, the invoker, holds CartCommand objects. AddItem, RemoveItem and ApplyCoupon implement CartCommand and act on the Cart receiver. The Client creates commands and passes them to CartHistory. invoker CartHistory - done: Deque<CartCommand> - undone: Deque<CartCommand> + run(command) + undo(), redo() stores 0..* «interface» CartCommand + execute(): void + undo(): void + label(): String implements AddItem RemoveItem ApplyCoupon acts on receiver Cart + add(), reduce(), remove(), applyCoupon() Client run(command) «create»
Command: the invoker stores and runs CartCommand objects, and each concrete command knows which receiver method to call.
  1. CartHistory (invoker) stores commands typed as the CartCommand interface, so it works with any command.
  2. Three concrete commands implement the interface (dashed line, hollow triangle).
  3. Each concrete command holds a reference to the Cart receiver and calls its methods.
  4. The client creates commands and passes them to the invoker. The invoker never calls the cart directly.

5. Step-by-Step Execution Flow

  1. The client creates new RemoveItem(cart, "SKU-HEADPHONES").
  2. It calls history.run(command).
  3. The invoker calls command.execute(); the command calls cart.remove() and stores the removed quantity.
  4. The invoker pushes the command onto its "done" stack and clears the "undone" stack.
  5. Later the client calls history.undo(). The invoker pops the command and calls undo(), which puts the headphones back with the stored quantity.
  6. The command moves to the "undone" stack, so redo() can execute it again.

6. Real-World Use Cases

  • E-commerce: undoable cart and checkout edits, and admin bulk actions recorded for audit.
  • Payments and banking: standing instructions, scheduled transfers and batch jobs stored as instruction objects and executed by a processor.
  • Notifications: "send" requests queued as commands and retried by a worker.
  • The JDK: Runnable and Callable objects submitted to an ExecutorService are commands, and the executor is the invoker. Swing's Action interface and javax.swing.undo.UndoManager with UndoableEdit implement commands and undo history.
  • Enterprise architecture: in CQRS, a command such as PlaceOrder is a message object handled by a command handler; frameworks such as Axon dispatch them with @CommandHandler. Sagas pair each step with a compensating action.

7. Problem Without the Pattern

UI handlers that change the cart directly:

CartWithoutCommand.java
import java.util.LinkedHashMap;
import java.util.Map;

public class CartWithoutCommand {

    static final class Cart {
        final Map<String, Integer> items = new LinkedHashMap<>();
        String coupon = null;
    }

    // Each UI handler changes the cart directly and forgets what it did
    static void onAddClicked(Cart cart, String sku) { cart.items.merge(sku, 1, Integer::sum); }
    static void onRemoveClicked(Cart cart, String sku) { cart.items.remove(sku); }
    static void onCouponApplied(Cart cart, String code) { cart.coupon = code; }

    public static void main(String[] args) {
        Cart cart = new Cart();
        onAddClicked(cart, "SKU-HEADPHONES");
        onAddClicked(cart, "SKU-CASE");
        onRemoveClicked(cart, "SKU-HEADPHONES");          // a mistake the shopper wants to undo
        onCouponApplied(cart, "FEST10");
        System.out.println("Cart: " + cart.items + ", coupon " + cart.coupon);
        System.out.println("Undo? Not possible: no handler recorded what it changed.");
    }
}
Console
Cart: {SKU-CASE=1}, coupon FEST10
Undo? Not possible: no handler recorded what it changed.
  • No memory of actions: undo, redo and audit are impossible.
  • Tight coupling: each UI handler knows exactly how to change the cart.
  • Duplication: adding undo would mean every handler storing its own "before" state in its own way.
  • No deferral: actions cannot be queued, scheduled or replayed.

8. Solution Using the Pattern

Wrap each action in a command object with execute() and undo(), and let an invoker run them and keep the history. The UI only creates commands.

Undo and redo now work for every action through two stacks. Each command stores exactly what it needs to reverse itself, such as the removed quantity or the previous coupon. A new action is one new class, and the history automatically supports it. The same command objects could be logged or sent to a server.

9. Command Design Pattern in Java: Code Examples

Each example is a single file that runs on Java 21 with java FileName.java.

Basic Example: Cart Undo and Redo

Problem: fix section 7 so that shoppers can undo and redo cart changes.

CartUndoRedoDemo.java
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedHashMap;
import java.util.Map;

public class CartUndoRedoDemo {

    // Receiver: the object that actually changes
    static final 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) {
            items.computeIfPresent(sku, (k, current) -> current > qty ? current - qty : null);   // null removes the entry
        }

        int remove(String sku) {                         // returns the removed quantity so undo can restore it
            Integer qty = items.remove(sku);
            return qty == null ? 0 : qty;
        }

        String applyCoupon(String code) {
            String previous = coupon;
            coupon = code;
            return previous;
        }

        @Override
        public String toString() { return items + (coupon == null ? "" : " coupon=" + coupon); }
    }

    // Command
    interface CartCommand {
        void execute();
        void undo();
        String label();
    }

    // Concrete commands: each remembers what it needs to reverse itself
    record AddItem(Cart cart, String sku, int qty) implements CartCommand {
        public void execute() { cart.add(sku, qty); }
        public void undo() { cart.reduce(sku, qty); }
        public String label() { return "add " + qty + " x " + sku; }
    }

    static final class RemoveItem implements CartCommand {
        private final Cart cart;
        private final String sku;
        private int removedQty;                          // captured at execute time

        RemoveItem(Cart cart, String sku) { this.cart = cart; this.sku = sku; }

        public void execute() { removedQty = cart.remove(sku); }
        public void undo() { if (removedQty > 0) cart.add(sku, removedQty); }
        public String label() { return "remove " + sku; }
    }

    static final class ApplyCoupon implements CartCommand {
        private final Cart cart;
        private final String code;
        private String previous;

        ApplyCoupon(Cart cart, String code) { this.cart = cart; this.code = code; }

        public void execute() { previous = cart.applyCoupon(code); }
        public void undo() { cart.applyCoupon(previous); }
        public String label() { return "apply coupon " + code; }
    }

    // Invoker: runs commands and keeps the history
    static final class CartHistory {
        private final Deque<CartCommand> done = new ArrayDeque<>();
        private final Deque<CartCommand> undone = new ArrayDeque<>();

        void run(CartCommand command) {
            command.execute();
            done.push(command);
            undone.clear();                              // a new action invalidates the redo history
        }

        void undo() {
            if (done.isEmpty()) return;
            CartCommand command = done.pop();
            command.undo();
            undone.push(command);
            System.out.println("  undo: " + command.label());
        }

        void redo() {
            if (undone.isEmpty()) return;
            CartCommand command = undone.pop();
            command.execute();
            done.push(command);
            System.out.println("  redo: " + command.label());
        }
    }

    public static void main(String[] args) {
        Cart cart = new Cart();
        CartHistory history = new CartHistory();

        history.run(new AddItem(cart, "SKU-HEADPHONES", 1));
        history.run(new AddItem(cart, "SKU-CASE", 2));
        history.run(new RemoveItem(cart, "SKU-HEADPHONES"));
        history.run(new ApplyCoupon(cart, "FEST10"));
        System.out.println("After 4 actions: " + cart);

        history.undo();
        history.undo();                                  // brings the headphones back
        System.out.println("After 2 undos:   " + cart);

        history.redo();
        System.out.println("After 1 redo:    " + cart);
    }
}

Important classes and methods

  • AddItem is a record because it needs no extra state; RemoveItem and ApplyCoupon capture "before" values in execute().
  • CartHistory uses two ArrayDeque stacks. Running a new command clears the redo stack, as in any editor.
  • The receiver methods return what changed, which makes undo straightforward.

Expected output

Console
After 4 actions: {SKU-CASE=2} coupon=FEST10
  undo: apply coupon FEST10
  undo: remove SKU-HEADPHONES
After 2 undos:   {SKU-CASE=2, SKU-HEADPHONES=1}
  redo: remove SKU-HEADPHONES
After 1 redo:    {SKU-CASE=2}

How it runs

  1. Four commands run; the headphones are added then removed, and a coupon is applied.
  2. Two undos remove the coupon and restore the headphones.
  3. One redo removes the headphones again.

10. Best Practices and Common Mistakes

Best practices

  • Keep commands small and focused; let the receiver hold the business logic.
  • Capture the "before" state in execute() so undo() is exact.
  • Make queued commands immutable data, so they can be serialised, logged and retried.
  • Thread safety: an invoker shared across threads needs synchronised history, and receivers touched by several workers need their own protection. A single-thread executor is the simplest way to guarantee ordering.

Common mistakes

  • Undo that recomputes instead of restoring stored state, which breaks when the receiver changed meanwhile.
  • Unbounded history that grows for the whole session.
  • Non-idempotent queued commands that double-charge when redelivered.
  • Overengineering: a command class for every method call when nothing is queued, logged or undone.

11. When to Use and When Not to Use

Use it when you need history (undo, audit, replay), deferral (queues, schedules, retries), or a uniform way for a UI, scheduler or message consumer to trigger many different actions.

Avoid it for simple direct calls with no need to store or delay them, where an extra class per action only adds noise. A lambda or Runnable is often enough when you only need deferred execution and no undo.

12. Advantages and Disadvantages

Advantages

  • Decouples the trigger from the action.
  • Undo, redo, audit and replay become straightforward.
  • Queuing and scheduling with ordinary executors or message queues.
  • Composable through macro commands.

Disadvantages

  • Many small classes, one per action.
  • Undo can be hard for actions with external side effects, such as sent emails.
  • Indirection: the call path is less obvious.

13. Comparison with Similar Patterns

AspectCommandStrategyMementoChain of Responsibility
IntentRepresent a request as an objectChoose how a task is doneCapture an object's state to restore itFind the handler for a request
Answers"What should happen, and to which object?""Which algorithm?""What was the state before?""Who handles this?"
Stored for laterYes: queued, logged, undoneUsually notYes: snapshotsNo
Typical pairingUses Memento for undoInjected into a contextSupports Command undoPasses commands along

A Command and a Strategy can look identical, an object with one method. The difference is intent: a command is a specific request with its data and target; a strategy is an interchangeable algorithm used by a context. Use Memento with Command when undo needs a snapshot, and send commands through a chain when several handlers might process them. See also the Template Method pattern, which fixes the steps of an algorithm instead of packaging requests.

14. Summary

  • The command design pattern in Java turns requests into objects with execute() and often undo().
  • Purpose: decouple triggering from executing, and make requests storable.
  • Components: Command, Concrete Command, Receiver, Invoker, Client.
  • The invoker runs commands and may keep them for undo, retry or audit.
  • Used for undo/redo, job queues, scheduled instructions, sagas and every Runnable you submit.
  • Benefits: history, deferral, composition and loose coupling.
  • Make queued commands immutable and idempotent, bound undo history, and skip it for simple calls.

15. Java Design Pattern Interview Questions and Answers

Q1. A Runnable is already a command. Why would you write your own Command interface?

Runnable covers "execute later", but it has no undo(), no description for logs, no identifier for idempotency, and lambdas are not reliably serialisable for queues. A custom interface adds exactly what your invoker needs. When you only need deferred execution, a Runnable or lambda is the simplest correct choice.

executor.submit(() -> ledger.move("SALARY", "SAVINGS", 30_000));   // fine: no undo or audit needed
Q2. How do you undo an action that has no natural inverse, such as applying a complex pricing rule?

Capture a snapshot of the receiver's relevant state before executing, using the Memento pattern, and restore it on undo. This trades memory for simplicity and correctness. Keep snapshots small by storing only the fields the command can change.

Q3. Commands are sent through a message queue and may be delivered twice. How do you stay safe?

Give every command a unique ID and make the handler idempotent: record processed IDs in the same transaction as the business change, and skip IDs already seen. Most brokers guarantee at-least-once delivery, so duplicates must be expected, not prevented.

Q4. An editor's undo history uses too much memory in long sessions. What do you do?

Bound the history, for example keep the last 100 commands and drop the oldest when a new one arrives. Merge small consecutive commands, such as many single-character edits, into one. Store compact data in each command instead of full snapshots.

Q5. Several threads submit commands to one invoker. What can go wrong?

The invoker's history stacks and the receiver can be corrupted by concurrent access, and commands may run in an unexpected order. Either confine execution to one thread, as the single-thread executor in the Practical Example does, or synchronise the invoker and make receivers thread-safe. Immutable command objects avoid a whole class of these bugs.