Command Design Pattern in Java
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
| Component | Responsibility | In the Basic Example |
|---|---|---|
| Command | Interface with execute() and, optionally, undo() | CartCommand |
| Concrete Command | Holds the receiver and the data, and calls the receiver | AddItem, RemoveItem, ApplyCoupon |
| Receiver | The object that does the real work | Cart |
| Invoker | Runs commands and may store them for undo, retry or audit | CartHistory |
| Client | Creates commands, wires them to receivers, and hands them to the invoker | main |
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.
CartCommand objects, and each concrete command knows which receiver method to call.CartHistory(invoker) stores commands typed as theCartCommandinterface, so it works with any command.- Three concrete commands implement the interface (dashed line, hollow triangle).
- Each concrete command holds a reference to the
Cartreceiver and calls its methods. - The client creates commands and passes them to the invoker. The invoker never calls the cart directly.
5. Step-by-Step Execution Flow
- The client creates
new RemoveItem(cart, "SKU-HEADPHONES"). - It calls
history.run(command). - The invoker calls
command.execute(); the command callscart.remove()and stores the removed quantity. - The invoker pushes the command onto its "done" stack and clears the "undone" stack.
- Later the client calls
history.undo(). The invoker pops the command and callsundo(), which puts the headphones back with the stored quantity. - 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:
RunnableandCallableobjects submitted to anExecutorServiceare commands, and the executor is the invoker. Swing'sActioninterface andjavax.swing.undo.UndoManagerwithUndoableEditimplement commands and undo history. - Enterprise architecture: in CQRS, a command such as
PlaceOrderis 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:
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.");
}
}
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.
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
AddItemis a record because it needs no extra state;RemoveItemandApplyCouponcapture "before" values inexecute().CartHistoryuses twoArrayDequestacks. Running a new command clears the redo stack, as in any editor.- The receiver methods return what changed, which makes undo straightforward.
Expected output
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
- Four commands run; the headphones are added then removed, and a coupon is applied.
- Two undos remove the coupon and restore the headphones.
- One redo removes the headphones again.
Practical Example: Queued Bank Instructions
Problem: a customer's month-end instructions are saved in advance and executed later, strictly in order, with a clear result for each. A failure must not stop the remaining instructions.
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class StandingInstructionsDemo {
// Receiver: a tiny ledger
static final class Ledger {
private final Map<String, Long> balances = new TreeMap<>();
Ledger(Map<String, Long> opening) { balances.putAll(opening); }
void move(String from, String to, long amount) {
long available = balances.getOrDefault(from, 0L);
if (available < amount) {
throw new IllegalStateException("insufficient funds in " + from + " (" + available + " < " + amount + ")");
}
balances.put(from, available - amount);
balances.merge(to, amount, Long::sum);
}
Map<String, Long> balances() { return new TreeMap<>(balances); }
}
// Command: an instruction that can be stored, queued and executed later
interface BankCommand {
String describe();
void execute(Ledger ledger);
}
record Transfer(String from, String to, long amount) implements BankCommand {
public String describe() { return "transfer " + amount + " " + from + " -> " + to; }
public void execute(Ledger ledger) { ledger.move(from, to, amount); }
}
record PayBill(String from, String biller, long amount) implements BankCommand {
public String describe() { return "pay " + biller + " " + amount + " from " + from; }
public void execute(Ledger ledger) { ledger.move(from, "BILLER:" + biller, amount); }
}
// Macro command: a list of commands treated as one
record Batch(String name, List<BankCommand> steps) implements BankCommand {
public String describe() { return "batch '" + name + "' (" + steps.size() + " steps)"; }
public void execute(Ledger ledger) { steps.forEach(step -> step.execute(ledger)); }
}
// Invoker: one worker thread runs queued commands in order and keeps an audit log
static final class InstructionProcessor implements AutoCloseable {
private final ExecutorService worker = Executors.newSingleThreadExecutor(); // strict ordering
private final Ledger ledger;
InstructionProcessor(Ledger ledger) { this.ledger = ledger; }
Future<String> submit(BankCommand command) {
return worker.submit(() -> {
try {
command.execute(ledger);
return "OK " + command.describe();
} catch (IllegalStateException e) {
return "FAILED " + command.describe() + ": " + e.getMessage();
}
});
}
@Override
public void close() { worker.close(); }
}
public static void main(String[] args) throws Exception {
Ledger ledger = new Ledger(Map.of("SAVINGS", 50_000L, "SALARY", 80_000L));
List<BankCommand> monthEnd = List.of(
new Transfer("SALARY", "SAVINGS", 30_000),
new Batch("utilities", List.of(new PayBill("SAVINGS", "POWER", 2_400), new PayBill("SAVINGS", "BROADBAND", 999))),
new Transfer("SAVINGS", "SIP-FUND", 10_000),
new Transfer("SALARY", "RENT", 60_000)); // fails: only 50,000 left in SALARY
List<Future<String>> results = new ArrayList<>();
try (InstructionProcessor processor = new InstructionProcessor(ledger)) {
monthEnd.forEach(command -> results.add(processor.submit(command))); // queued, run later
for (Future<String> result : results) {
System.out.println(result.get());
}
}
System.out.println("Balances: " + ledger.balances());
}
}
Important classes and methods
TransferandPayBillare records: plain, immutable data that could be stored in a database or sent as JSON.Batchis a macro command: a command made of commands, executed as one item.InstructionProcessoris the invoker. A single-thread executor guarantees ordering, and only that one thread touches the ledger.
Expected output
OK transfer 30000 SALARY -> SAVINGS
OK batch 'utilities' (2 steps)
OK transfer 10000 SAVINGS -> SIP-FUND
FAILED transfer 60000 SALARY -> RENT: insufficient funds in SALARY (50000 < 60000)
Balances: {BILLER:BROADBAND=999, BILLER:POWER=2400, SALARY=50000, SAVINGS=66601, SIP-FUND=10000}
How it runs
- All four commands are queued first, then executed one by one on the worker thread.
- The utilities batch runs its two bill payments as one queued item.
- The rent transfer fails because SALARY has only 50,000 left, and the failure is reported without stopping anything.
The batch is not atomic: if its second payment failed, the first would stay done. The Enterprise Example adds compensation for that.
Real-World Enterprise Example: Order Saga with Compensating Commands
Problem: placing an order touches stock, payment and shipping, which live in different services, so no single database transaction covers them. If a step fails, completed steps must be reversed, and a retried request must not place the order twice.
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
public class OrderSagaDemo {
// Command with a compensating action
interface Step {
String name();
void execute(OrderContext order);
void compensate(OrderContext order);
}
// Shared data for one order run
static final class OrderContext {
final String orderId;
final long amount;
final boolean paymentWillFail;
final List<String> log = new ArrayList<>();
OrderContext(String orderId, long amount, boolean paymentWillFail) {
this.orderId = orderId;
this.amount = amount;
this.paymentWillFail = paymentWillFail;
}
}
// Concrete commands (the receivers are simulated with log lines)
static final class ReserveStock implements Step {
public String name() { return "reserve-stock"; }
public void execute(OrderContext o) { o.log.add("stock reserved"); }
public void compensate(OrderContext o) { o.log.add("stock released"); }
}
static final class ChargePayment implements Step {
public String name() { return "charge-payment"; }
public void execute(OrderContext o) {
if (o.paymentWillFail) throw new IllegalStateException("card declined");
o.log.add("charged " + o.amount);
}
public void compensate(OrderContext o) { o.log.add("refunded " + o.amount); }
}
static final class CreateShipment implements Step {
public String name() { return "create-shipment"; }
public void execute(OrderContext o) { o.log.add("shipment created"); }
public void compensate(OrderContext o) { o.log.add("shipment cancelled"); }
}
// Invoker: runs steps in order; on failure, compensates completed steps in reverse
static final class SagaRunner {
private final List<Step> steps;
private final Set<String> processedOrders = ConcurrentHashMap.newKeySet(); // idempotency guard
SagaRunner(List<Step> steps) { this.steps = List.copyOf(steps); }
String run(OrderContext order) {
if (!processedOrders.add(order.orderId)) {
return order.orderId + ": duplicate request ignored";
}
Deque<Step> completed = new ArrayDeque<>();
for (Step step : steps) {
try {
step.execute(order);
completed.push(step);
} catch (RuntimeException e) {
order.log.add(step.name() + " failed: " + e.getMessage());
while (!completed.isEmpty()) {
completed.pop().compensate(order); // undo in reverse order
}
return order.orderId + ": ROLLED BACK " + order.log;
}
}
return order.orderId + ": COMPLETED " + order.log;
}
}
public static void main(String[] args) {
SagaRunner placeOrder = new SagaRunner(List.of(new ReserveStock(), new ChargePayment(), new CreateShipment()));
System.out.println(placeOrder.run(new OrderContext("ORD-71", 2_499, false)));
System.out.println(placeOrder.run(new OrderContext("ORD-72", 89_999, true)));
System.out.println(placeOrder.run(new OrderContext("ORD-71", 2_499, false))); // client retried
}
}
Important classes and methods
Stepis a command withexecute()andcompensate(). Compensation is a business-level undo, such as a refund, not a database rollback.SagaRunneris the invoker. It pushes each completed step on a stack and, on failure, compensates them in reverse order.- A concurrent set of processed order IDs makes the runner idempotent for retries.
Expected output
ORD-71: COMPLETED [stock reserved, charged 2499, shipment created]
ORD-72: ROLLED BACK [stock reserved, charge-payment failed: card declined, stock released]
ORD-71: duplicate request ignored
How it runs
- ORD-71 runs all three steps and completes.
- ORD-72's payment is declined, so the only completed step, the stock reservation, is released.
- The retried ORD-71 is recognised and ignored.
In production the processed IDs and saga state live in a database, so they survive restarts and work across instances.
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()soundo()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
| Aspect | Command | Strategy | Memento | Chain of Responsibility |
|---|---|---|---|---|
| Intent | Represent a request as an object | Choose how a task is done | Capture an object's state to restore it | Find 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 later | Yes: queued, logged, undone | Usually not | Yes: snapshots | No |
| Typical pairing | Uses Memento for undo | Injected into a context | Supports Command undo | Passes 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 oftenundo(). - 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
Runnableyou 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 neededQ2. 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.