Behavioral PatternINTERMEDIATE7 min deep dive

Command Pattern Pattern

Encapsulates a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.

Real-World Mental Model / Metaphor:

A waiter in a restaurant taking your order on a slip of paper. The slip encapsulates your order request. It can be queued, passed to the chef, tracked, or cancelled before cooking.

Interactive Runtime Simulator

Test and tweak inputs dynamically

Interactive Command Pattern SimulatorLIVE PLAYGROUND

Interact with the controls below to see how this design pattern executes in memory at runtime.

Category: Behavioral
Configure Chain Handlers (Toggle Failures):
CHAIN PIPELINE STATUS
Step 1: AuthHandler.check() -> PASSED
Step 2: RateLimitHandler.check() -> PASSED
Step 3: PayloadGuard.check() -> PASSED
The Problem It Solves

Hardcoding business logic directly inside GUI buttons or API handlers, preventing undo/redo operations or deferred job queue execution.

The Architectural Solution

Define a Command interface with `execute()` and `undo()` methods. Concrete commands encapsulate the receiver and parameters.

Pattern Structure & Participants

ParticipantRole & ResponsibilityType
Command (Interface)Declares execute() and undo()interface
ConcreteCommandBinds receiver to actionclass
ReceiverKnows how to perform the actual work (e.g. Light, Database)class
InvokerTriggers command execution and tracks historyclass
Collaboration Rules:
  • Invoker stores command in undo stack
  • Invoker calls command.execute() -> Command calls receiver.action()

Production Code Implementation

Command Pattern.java
// 1. Command Interface
public interface Command {
    void execute();
    void undo();
}

// 2. Receiver
public class TextDocument {
    private String text = "";
    public void append(String str) { text += str; }
    public void delete(int length) { text = text.substring(0, text.length() - length); }
    public String getText() { return text; }
}

// 3. Concrete Command
public class InsertTextCommand implements Command {
    private final TextDocument doc;
    private final String textToInsert;

    public InsertTextCommand(TextDocument doc, String textToInsert) {
        this.doc = doc;
        this.textToInsert = textToInsert;
    }

    public void execute() { doc.append(textToInsert); }
    public void undo() { doc.delete(textToInsert.length()); }
}

// 4. Invoker with Undo Stack
public class TextEditorInvoker {
    private final Deque<Command> history = new ArrayDeque<>();

    public void executeCommand(Command cmd) {
        cmd.execute();
        history.push(cmd);
    }

    public void undo() {
        if (!history.isEmpty()) {
            Command lastCmd = history.pop();
            lastCmd.undo();
        }
    }
}
When to Use:
  • •When you want to parameterize objects with operations (callbacks).
  • •When you need to queue operations, schedule their execution, or execute them over a network.
  • •When you need to support reversible operations (Undo / Redo).
When to Avoid (Anti-Pattern):
  • •When actions are synchronous and immediate with no need for queuing, undo, or history tracking.

Staff Engineering Interview Insights & Gotchas

  • Explain how Command Pattern is the foundation of Event Sourcing and Sagas in distributed systems.
  • Show how an Invoker can maintain a Stack for undo and a Queue for asynchronous background workers.