Skip to main content

What does the Command pattern do and why is it needed?

Command is a behavioral pattern that turns a request or action into a separate object, encapsulating all the information needed to execute it.


1. The Core Idea

Instead of calling methods directly, the program creates a command object that stores:

  • a reference to the receiver (the object that will perform the action),
  • the action itself,
  • and the parameters it needs.

Such an object can be passed around, queued, canceled, or repeated - all without knowing how the operation is actually performed.

Idea: "pack an action into an object".


2. Why It's Needed

  • To decouple a request from its executor.
  • To be able to delay execution, queue, or cancel an action.
  • To implement an operation history, macros, "undo/redo", transactions.

3. Structure

  • Command - an interface with an execute() method.
  • ConcreteCommand - a specific command that calls the needed method on the receiver.
  • Receiver - the object that knows how to perform the action.
  • Invoker - the initiator that triggers the command (for example, a button).
  • Client - creates the command and passes it to the invoker.

4. Example (Java)

java
interface Command { void execute(); } class Light { void turnOn() { System.out.println("Light turned on"); } void turnOff() { System.out.println("Light turned off"); } } class TurnOnCommand implements Command { private Light light; public TurnOnCommand(Light light) { this.light = light; } public void execute() { light.turnOn(); } } class RemoteControl { private Command command; public void setCommand(Command command) { this.command = command; } public void pressButton() { command.execute(); } } // Usage Light light = new Light(); Command on = new TurnOnCommand(light); RemoteControl remote = new RemoteControl(); remote.setCommand(on); remote.pressButton();

5. Advantages

  • Allows you to decouple the client from the execution logic.
  • Supports queues, history, undo/redo.
  • Simplifies adding new commands without changing existing code.
  • Fits GUI buttons, menus, task schedulers.

Conclusion

Command is needed to represent an action as an object that can be executed, undone, logged, and combined, thereby making the system flexible, extensible, and controllable over time.

Short Answer

Interview ready
Premium

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