About Us Contact Us Write for Us Advertise
Home > System Design > Low-Level Design > Command Pattern in Java (with Undo Example)
System Design › Low-Level Design

Command Pattern in Java (with Undo Example)

The Command pattern explained: wrap a request as an object with execute() and undo(), decoupling invoker from receiver — unlocking undo/redo, queuing, logging, and macros. Java code, UML, when to use.

Shiv Pandey
Shiv Pandey
Oct 23, 2026 | 76 views
Command Pattern in Java (with Undo Example)

🟠 Design Patterns · Behavioral · Senior

The Command pattern turns a request into a standalone object. Instead of calling light.on() directly, you wrap that action in a Command object you can pass around, store in a queue, log, or undo. It's the pattern behind undo/redo, task queues, and the buttons on a remote control — anywhere you want to decouple "what to do" from "when and who does it."

In one line: Command encapsulates a request as an object with an execute() method, decoupling the sender (invoker) from the receiver — which unlocks queuing, logging, and undo/redo of operations.

The problem

A remote control has buttons that should trigger actions — turn on a light, open a garage, start a fan. If each button hardcodes its action, the remote is tightly coupled to every device, and you can't reassign buttons, queue actions, or undo them. You want a button to just "hold a command" it can fire, without knowing what it does.

The solution: wrap the action in an object

🟠 Define a Command interface with execute(); each concrete command holds a receiver and calls the right method on it; an invoker (the button) just calls execute():

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

class LightOnCommand implements Command {          // wraps receiver + action
    private final Light light;
    LightOnCommand(Light l){ this.light = l; }
    public void execute(){ light.on(); }
    public void undo(){ light.off(); }
}
class Button {                                     // the invoker
    private Command command;
    void setCommand(Command c){ this.command = c; }
    void press(){ command.execute(); }             // doesn't know what it does
}
// wire and fire:
Button b = new Button();
b.setCommand(new LightOnCommand(livingRoomLight));
b.press();     // light on
Button(invoker) LightOnCommandexecute()/undo() Light(receiver) execute() on()

The button is now decoupled from the light — you can assign any command to it, and swap them at runtime. That decoupling is the foundation for the powerful features below.

What Command unlocks

🔴 Because a request is now an object, you can do things impossible with a direct method call:

  • Undo/redo: add an undo() to each command and keep a history stack. To undo, pop the last command and call its undo(). This is exactly how editors implement Ctrl+Z.
  • Queuing & scheduling: put commands on a queue and execute later or on worker threads — the basis of task/job queues and thread pools (a Runnable is essentially a command).
  • Logging & replay: record executed commands to a log; replay them to reconstruct state after a crash.
  • Macros: a command that runs a list of other commands (composite command).

Naming undo/redo and "a Runnable is a command" shows you understand why this pattern matters, not just its shape.

Where you meet it

GUI menu items and buttons, text-editor undo stacks, transaction logs, task/job queues, thread pools (Runnable/Callable), and the "actions" in many frameworks are all Command. Any time an operation is treated as a first-class thing you store or pass around, that's Command.

When to use it

Use Command when you need to parameterize objects with actions, queue or schedule operations, support undo/redo, or log requests. If you just need to call a method once and never store, queue, or reverse it, a direct call is simpler — the value of Command is treating the request as an object.

The interview-ready summary

"Command wraps a request as an object with an execute() (and often undo()), holding a receiver and the action to run. An invoker triggers execute() without knowing the details, so the sender and receiver are decoupled. Because the request is now an object, I get undo/redo (a history stack of commands), queuing/scheduling, logging and replay, and macros. Java's Runnable in a thread pool is essentially Command." That covers the mechanism and the high-value use cases."

What to read next

← State pattern · Template Method pattern →

Related Articles

Chain of Responsibility Pattern in Java (Example)
System Design › Low-Level Design

Chain of Responsibility Pattern in Java (Example)

Template Method Pattern in Java (with Example)
System Design › Low-Level Design

Template Method Pattern in Java (with Example)

State Pattern in Java (with Example)
System Design › Low-Level Design

State Pattern in Java (with Example)

Observer Pattern in Java (with Example)
System Design › Low-Level Design

Observer Pattern in Java (with Example)