Chaturmind
LearnDSASystem DesignInterview PrepDevOpsEngineering GrowthBlog
Start learning
Chaturmind

Structured learning paths for engineers who want to go deep. Written by practitioners.

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML
  • DevOps
  • Engineering Growth
  • Java Interview Prep

Company

  • Blog
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Chaturmind. All rights reserved.

Built for engineers who want to go deep.


← Java Interview Prep: 5–8 Years

Advanced Core Java

  • Advanced OOP & Design Scenarios — Interview Questions
  • Advanced Concurrency, Collections & Memory — Interview Questions
  • Modern Java Language Features & Annotations — Interview Questions
  • Class Loading, Reflection, Serialization & Idioms — Interview Questions

Java Design Patterns in Depth

  • Design Patterns Overview & Singleton — Interview Questions
  • Factory & Abstract Factory Patterns — Interview Questions
  • Builder & Prototype Patterns — Interview Questions
  • Adapter & Bridge Patterns — Interview Questions
  • Composite & Decorator Patterns — Interview Questions
  • Facade & Proxy Patterns — Interview Questions
  • Chain of Responsibility & Observer Patterns — Interview Questions
  • Strategy & Template Method Patterns — Interview Questions
  • Command Pattern — Interview Questions

Advanced Spring Boot

  • Logging, Configuration & Actuator (Advanced) — Interview Questions
  • Transactions, Multiple Datasources & Query Tuning — Interview Questions
  • Validation & REST API Design (Advanced) — Interview Questions
  • Reactive, Async & Scheduling in Spring Boot — Interview Questions
  • Deployment, High Availability, Scaling & Caching — Interview Questions
Chaturmind
← Java Interview Prep: 5–8 Years

Advanced Core Java

  • Advanced OOP & Design Scenarios — Interview Questions
  • Advanced Concurrency, Collections & Memory — Interview Questions
  • Modern Java Language Features & Annotations — Interview Questions
  • Class Loading, Reflection, Serialization & Idioms — Interview Questions

Java Design Patterns in Depth

  • Design Patterns Overview & Singleton — Interview Questions
  • Factory & Abstract Factory Patterns — Interview Questions
  • Builder & Prototype Patterns — Interview Questions
  • Adapter & Bridge Patterns — Interview Questions
  • Composite & Decorator Patterns — Interview Questions
  • Facade & Proxy Patterns — Interview Questions
  • Chain of Responsibility & Observer Patterns — Interview Questions
  • Strategy & Template Method Patterns — Interview Questions
  • Command Pattern — Interview Questions

Advanced Spring Boot

  • Logging, Configuration & Actuator (Advanced) — Interview Questions
  • Transactions, Multiple Datasources & Query Tuning — Interview Questions
  • Validation & REST API Design (Advanced) — Interview Questions
  • Reactive, Async & Scheduling in Spring Boot — Interview Questions
  • Deployment, High Availability, Scaling & Caching — Interview Questions
HomeLearnJava Interview PrepJava Interview Prep: 5–8 YearsJava Design Patterns in Depth
✓ FreeAdvanced· 6 min read

Command Pattern — Interview Questions

The Command pattern — encapsulating requests as objects, the invoker/command/receiver roles, a Java implementation, undo/redo with command history, queuing/scheduling/logging commands, advantages in event-driven systems, how it decouples sender and receiver, and how it relates to CQRS commands, Runnable and message queues.

Published September 25, 2026


How to use this lesson

Command turns a request into an object. Once it's an object, you can pass it around, queue it, log it, retry it, schedule it and undo it. In Java you already use it:

  • Runnable/Callable submitted to an executor;
  • Spring Batch steps;
  • messages on a queue;
  • the "commands" in CQRS.

The interview checklist is the roles (client, invoker, command, receiver) and undo/redo.

Q1. What is the Command pattern for?

Short answer: It encapsulates a request as an object, containing everything needed to perform it later: the receiver, the action and the parameters. This lets you parameterise objects with requests, queue or schedule them, log them, and support undo/redo. For example, in a text editor, Copy, Paste and Delete are each a command object that can be executed, stored in a history and reversed.

Learn it in depth → Command Pattern

Q2. What is the Command pattern, and how does it encapsulate requests?

Short answer: It has four roles:

  • A Command interface: execute(), and optionally undo().
  • Concrete commands: each holds a reference to its receiver, plus the arguments, and implements execute() by calling the receiver.
  • An Invoker: a button, scheduler, queue consumer or job runner. It holds commands and calls execute() without knowing what they do.
  • A Client: creates the commands, and wires them to receivers and invokers.

The request, "what to do, to whom, with what", is now a first-class value.

Q3. How would you implement the Command pattern in Java?

Short answer:

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

public final class TextDocument {                                   // the receiver: the real logic
    private final StringBuilder text = new StringBuilder();
    public void insert(int pos, String s) { text.insert(pos, s); }
    public void delete(int pos, int len) { text.delete(pos, pos + len); }
    public String slice(int pos, int len) { return text.substring(pos, pos + len); }
}

public final class InsertText implements Command {
    private final TextDocument doc; private final int pos; private final String s;
    public InsertText(TextDocument doc, int pos, String s) { this.doc = doc; this.pos = pos; this.s = s; }
    public void execute() { doc.insert(pos, s); }
    public void undo()    { doc.delete(pos, s.length()); }
}

public final class DeleteText implements Command {
    private final TextDocument doc; private final int pos, len; private String removed;   // state captured for undo
    public DeleteText(TextDocument doc, int pos, int len) { this.doc = doc; this.pos = pos; this.len = len; }
    public void execute() { removed = doc.slice(pos, len); doc.delete(pos, len); }
    public void undo()    { doc.insert(pos, removed); }
}

public final class Editor {                                          // the invoker, with history
    private final Deque<Command> undo = new ArrayDeque<>(), redo = new ArrayDeque<>();
    public void run(Command c) { c.execute(); undo.push(c); redo.clear(); }   // a new action invalidates redo
    public void undo() { if (!undo.isEmpty()) { Command c = undo.pop(); c.undo(); redo.push(c); } }
    public void redo() { if (!redo.isEmpty()) { Command c = redo.pop(); c.execute(); undo.push(c); } }
}

Key points to cover:

  • The textbook example is a remote control (the invoker), with LightOnCommand calling light.on() on the Light receiver. It has the same roles as the code above.

Q4. When would you use the Command pattern, for example for undo/redo?

Short answer:

  • Undo/redo: editors, drawing tools, form wizards. Each executed command goes on an undo stack, and knows how to reverse itself, capturing whatever state it needs at execute time.
  • Queuing and asynchronous work: jobs submitted to an executor or a message queue.
  • Scheduling: run this command at 2 a.m.
  • Retries: re-execute a failed command.
  • Audit logging and replay: persist commands, then replay them to rebuild state.
  • Transactions or macros: a composite command that runs several commands, rolling back the executed ones on failure.
  • GUI actions: the same command bound to a menu item, a toolbar button and a shortcut.

Q5. What are the advantages of the Command pattern in event-driven systems?

Short answer:

  • Decoupling: the component that raises an action doesn't know who performs it.
  • Uniform handling: every action goes through the same pipeline (validate, authorise, log, execute, emit), so cross-cutting concerns are written once.
  • Serialisable requests: commands can be put on queues, persisted and retried with idempotency keys.
  • Extensibility: new behaviour means a new command class and handler.
  • Replay and audit from a command log.

Q6. How does the Command pattern decouple the sender and receiver of a request?

Short answer: The sender (invoker) only knows the Command interface, and calls execute(). The command knows the receiver and the method to call, and the receiver knows nothing about the sender. So:

  • the same invoker (a button or a job runner) can trigger any action;
  • the same action can be triggered by any invoker;
  • either side can change independently.

With a queue in between, the sender and receiver are also decoupled in time and in process.

Q7. How does Command relate to things you use every day in Java and Spring?

Short answer:

  • Runnable/Callable are command interfaces, and an ExecutorService is the invoker: executor.submit(() -> emailService.send(msg)).
  • CQRS commands (PlaceOrderCommand handled by a PlaceOrderHandler) are Commands in which the data object and the handler are separated, often dispatched through a bus.
  • Messages on Kafka or RabbitMQ carry serialised commands between services, with the consumer as the invoker.
  • Spring Batch Tasklets, and scheduled jobs (@Scheduled methods wrapped as runnables), are commands with an invoker.
public record PlaceOrderCommand(UUID idempotencyKey, UUID customerId, List<LineItem> items) { }

@Component
class PlaceOrderHandler {
    @Transactional
    public OrderId handle(PlaceOrderCommand cmd) {
        return processed.find(cmd.idempotencyKey())                       // safe to retry
                        .orElseGet(() -> orders.place(cmd.customerId(), cmd.items(), cmd.idempotencyKey()));
    }
}

Follow-up questions this topic invites — and their answers

Q: Command vs Strategy? A: A Strategy is how to do something (an interchangeable algorithm, called by a context). A Command is what to do (a request object, with a receiver and parameters, that can be stored, queued and undone). Commands are usually one-shot actions. Strategies are reusable algorithms.

Q: How do you implement undo for operations that can't be reversed, like sending an email? A: Use a compensating action: send a correction, cancel a booking, issue a refund. Or delay the irreversible effect (an outbox with a grace period, like "undo send"). Undo often means compensation, not literal reversal, in distributed systems too (sagas).

Q: What is a macro command? A: A composite command holding a list of commands. execute() runs them in order, and undo() undoes them in reverse order. If one fails midway, undo the already-executed ones to keep it all-or-nothing.

Q: Command vs Memento for undo? A: With Command, each action knows how to reverse itself (store the deltas). With Memento, you snapshot the receiver's state before the action, and restore it on undo. That's simpler for complex state, but uses more memory. Large editors combine them.

Previous

Strategy & Template Method Patterns — Interview Questions

Next

Logging, Configuration & Actuator (Advanced) — Interview Questions

AI Tutor

Lesson: Command Pattern — Interview Questions

Quick actions

AI responses can be inaccurate. Verify critical information.