Skip to main content

What classes are typically involved in implementing Command?

Implementing the Command pattern typically involves five key classes (or roles) that together provide execution, undo, and management of commands.


1. Command (Command Interface)

Defines a single contract for all commands - usually including the methods:

  • execute() - perform the action,
  • (optionally) undo() - reverse the action.

Example:

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

2. ConcreteCommand (Specific Command)

Implements the Command interface, encapsulating a specific action on a receiver object. Stores:

  • a reference to the Receiver,
  • the data needed to execute and undo the action.

Example:

java
class TurnOnCommand implements Command { private Light light; public TurnOnCommand(Light light) { this.light = light; } public void execute() { light.turnOn(); } public void undo() { light.turnOff(); } }

3. Receiver

The object that knows how to perform the operation. The command simply calls its methods without knowing exactly how they are implemented.

Example:

java
class Light { void turnOn() { System.out.println("Light turned on"); } void turnOff() { System.out.println("Light turned off"); } }

4. Invoker

The component that triggers the command, but does not know what it does. It can store the command, call execute() and undo(), and manage history.

Example:

java
class RemoteControl { private Command command; public void setCommand(Command command) { this.command = command; } public void pressButton() { command.execute(); } public void pressUndo() { command.undo(); } }

5. Client

Creates commands, links them to receivers, and passes them to the invoker. It knows which actions need to be performed but is not concerned with their implementation.

Example:

java
Light light = new Light(); Command turnOn = new TurnOnCommand(light); RemoteControl remote = new RemoteControl(); remote.setCommand(turnOn); remote.pressButton();

6. Overall Structure

javascript
Client InvokerCommandReceiver ConcreteCommand

Conclusion

ClassRole
CommandDefines the interface for executing (and undoing) actions
ConcreteCommandStores a reference to the receiver and implements a specific action
ReceiverKnows how to perform the operation
InvokerTriggers commands, manages history
ClientConfigures the links between commands and receivers

Summary: This structure lets you separate "what to do" from "how to do it", making the system flexible, extensible, and easy to manage - including for undo/redo, macros, and task queues.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.