100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace

What is the Command Pattern?

Learn the Command design pattern — invoker, command, receiver roles, undo/redo support — with a Java example and interview Q&A.

mediumQ37 of 226 in Object Oriented Programming Est. time: 5 minsLast updated:
Open Code Lab

Expected Interview Answer

The Command pattern encapsulates a request as a standalone object, bundling the receiver, the action to invoke, and its parameters, so callers can issue, queue, log, or undo operations without knowing how they are carried out.

A Command interface typically declares an execute() method, and each concrete command wraps a receiver plus the exact call needed to perform one action. An invoker holds a command reference and calls execute() without knowing the receiver or the operation details, which decouples the object that triggers an action from the object that performs it. Because each request is now a first-class object, commands can be queued, logged for auditing, transmitted across a network, or stored in a history stack to support undo and redo. Many command implementations also add an undo() method that reverses the same operation using state captured at execution time.

  • Decouples the invoker from the receiver of an action
  • Supports undo, redo, and operation history stacks
  • Enables queuing, logging, and deferred execution of requests
  • Makes new actions addable without changing invoker code

AI Mentor Explanation

A team captain writes a specific instruction on a card and hands it to the twelfth man to relay to a bowler — 'bowl a yorker at leg stump' — rather than walking out and doing it himself. The card is a self-contained command object: it names the action and the parameters, and the runner (invoker) delivers it without needing to understand bowling mechanics. If the plan fails, the coaching staff can review the stack of instruction cards afterward to see exactly what was called and in what order, just like a command history log.

Step-by-Step Explanation

  1. Step 1

    Define a Command interface

    Declare an execute() method (and optionally undo()) that every concrete command implements.

  2. Step 2

    Create concrete commands

    Each command wraps a receiver reference plus the exact parameters needed to perform one action.

  3. Step 3

    Give the invoker a command reference

    The invoker calls execute() on whatever command it holds, without knowing the receiver.

  4. Step 4

    Wire client to receiver and command

    The client constructs the receiver, wraps it in a command, and hands the command to the invoker.

What Interviewer Expects

  • A clear definition: a request turned into a first-class object
  • The three roles: invoker, command, receiver, and how they decouple
  • A concrete use case (undo/redo, queuing, logging, macro commands)
  • Awareness of how undo() typically works by storing prior state

Common Mistakes

  • Confusing Command with the Strategy pattern (Command encapsulates a request with a receiver; Strategy swaps an algorithm)
  • Putting business logic directly in the invoker instead of the receiver
  • Forgetting that undo requires the command to capture enough state before executing
  • Treating Command as only useful for GUI buttons, missing queuing and logging use cases

Best Answer (HR Friendly)

The Command pattern turns an action into an object of its own, with everything needed to perform it — who does it, what to do, and what parameters to use. This lets you hand that action around, queue it, log it, or undo it later, without the code that triggers the action needing to know how it actually gets done.

Code Example

Command pattern with undo support
interface Command {
    void execute();
    void undo();
}

class Light {
    void on() { System.out.println("Light ON"); }
    void off() { System.out.println("Light OFF"); }
}

class LightOnCommand implements Command {
    private final Light light;
    LightOnCommand(Light light) { this.light = light; }
    public void execute() { light.on(); }
    public void undo() { light.off(); }
}

class RemoteControl {
    private Command lastCommand;
    void submit(Command command) {
        command.execute();
        lastCommand = command;
    }
    void pressUndo() {
        if (lastCommand != null) lastCommand.undo();
    }
}

Light livingRoomLight = new Light();
RemoteControl remote = new RemoteControl();
remote.submit(new LightOnCommand(livingRoomLight)); // Light ON
remote.pressUndo();                                 // Light OFF

Follow-up Questions

  • How does the Command pattern support undo and redo?
  • How does Command differ from the Strategy pattern?
  • How would you implement a macro command that runs several commands in sequence?
  • Where might you use Command in a job-queue or task-scheduling system?

MCQ Practice

1. What is the primary purpose of the Command pattern?

Command wraps a request (receiver, action, parameters) into an object so the invoker never needs to know the receiver directly.

2. Which method do concrete Command implementations typically define to reverse an action?

By convention, Command implementations add an undo() method that reverses the effect of execute() using previously captured state.

3. In the Command pattern, which component actually performs the underlying business logic?

The receiver holds the real logic; the command object just wraps a call to it, and the invoker only triggers execute().

Flash Cards

Command pattern in one line?Encapsulate a request as an object so it can be issued, queued, logged, or undone independently of who triggers it.

Three key roles?Invoker (triggers), Command (wraps the request), Receiver (does the real work).

How is undo typically implemented?The command captures state before executing, then a separate undo() method restores it.

Common real-world use?GUI button actions, transaction logging, task queues, and undo/redo stacks.

1 / 4

Continue Learning