Knowledge Guide
HomeOO & Low-Level DesignBehavioral

Command Pattern

The Command pattern is a behavioral design pattern that encapsulates a request as an object, allowing users to parameterize clients with queues, requests, and operations. It transforms a request into an independent object with all the request's details. This separation enables more versatile operations such as queuing, logging, undoing actions, and delaying execution.

Consider an online shopping platform, which is a well-known experience for many people. You may be browsing, placing things in your cart, deciding to cancel your order, or perhaps changing your mind and exchanging an item for another. Without the proper system in place, these actions might turn into a chaotic mess for both the user and the underlying software architecture.

Applying the command pattern to it converts every action into a command object, such as adding, removing, or modifying an order. This object contains all of the components required to complete the task.

Real-World Example

A practical example of a Command Pattern is a smart home application. This application allows you to control different electronic devices, like TVs, lights, and air conditioners, with your phone.

The app presents a simple, user-friendly interface with buttons for every device or action. Each button acts as a command. Pressing a button sends a command to the corresponding device. Using the command pattern, it's easy to add some new devices to this app, hence increasing the flexibility of the application.

Command Pattern - Smart Home Application Example
Command Pattern - Smart Home Application Example

Structure of Command Pattern

The command pattern consists of the following key components:

Command Pattern - Class Diagram
Command Pattern - Class Diagram

Implementation of Command Pattern

This example demonstrates a simple light control system using the Command pattern. The system can turn a light on and off using commands.

Pseudocode

Interface Command { Method execute() } Class Light { Method turnOn() { Print "Light is ON" } Method turnOff() { Print "Light is OFF" } } Class TurnOnLightCommand implements Command { Private light: Light Constructor(light: Light) { this.light = light } Method execute() { light.turnOn() } } Class TurnOffLightCommand implements Command { Private light: Light Constructor(light: Light) { this.light = light } Method execute() { light.turnOff() } } Class RemoteControl { Private command: Command Method setCommand(command: Command) { this.command = command } Method pressButton() { command.execute() } } // Client Code Main { light = new Light() turnOn = new TurnOnLightCommand(light) turnOff = new TurnOffLightCommand(light) remote = new RemoteControl() remote.setCommand(turnOn) remote.pressButton() remote.setCommand(turnOff) remote.pressButton() }

Implementation

java
// Command Interface
interface Command {
  void execute();
}

// Receiver - Light
class Light {

  public void turnOn() {
    System.out.println("Light is ON");
  }

  public void turnOff() {
    System.out.println("Light is OFF");
  }
}

// Concrete Commands
class TurnOnLightCommand implements Command {

  private Light light;

  TurnOnLightCommand(Light light) {
    this.light = light;
  }

  public void execute() {
    light.turnOn();
  }
}

class TurnOffLightCommand implements Command {

  private Light light;

  TurnOffLightCommand(Light light) {
    this.light = light;
  }

  public void execute() {
    light.turnOff();
  }
}

// Invoker - RemoteControl
class RemoteControl {

  private Command command;

  void setCommand(Command command) {
    this.command = command;
  }

  void pressButton() {
    command.execute();
  }
}

// Client Code
public class Solution {

  public static void main(String[] args) {
    Light light = new Light();
    Command turnOn = new TurnOnLightCommand(light);
    Command turnOff = new TurnOffLightCommand(light);

    RemoteControl remote = new RemoteControl();
    remote.setCommand(turnOn);
    remote.pressButton();

    remote.setCommand(turnOff);
    remote.pressButton();
  }
}

Application of Command Pattern

Pros and Cons

ProsCons
Decoupling of Actions and Actors
Decouples the objects that send commands from the ones that perform them.
Complexity
It can increase the number of classes and complexity of the system.
Ease of Extending Commands
New commands can be added without modifying the existing commands.
Overhead
Each action might require a new command class, that increases overhead.
Simplifying Complex Operations
By breaking the complex operations into simpler commands, operations can be simplified.
Indirect Execution
Commands introduce an additional layer of abstraction, which can complicate understanding and debugging.
Support for Undo/Redo
Facilitates implementing undo/redo mechanisms.

The command pattern is a very useful tool in your design pattern toolbox. It's like possessing a magic wand that neatly condenses complex requests into small, doable objects. This leads to a world of possibilities, including the ability to undo functions, log actions, and much more, and make your code cleaner and more organized.

🤖 Don't fully get this? Learn it with Claude

Stuck on Command Pattern? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.

🎨 Explain it visually

Build the mental picture, not memorization.

I just read a lesson on **Command Pattern** (OO & Low-Level Design) and want to truly understand it. Explain Command Pattern from first principles using ONE vivid real-world analogy and a visual mental model — draw it as ASCII art or a clear step-by-step diagram — with a concrete example using real numbers. Then ask me one question to check I got the mental picture, and wait for my reply. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🤔 Walk me through it (interactive)

Socratic — adapts to where you're stuck.

Teach me **Command Pattern** interactively. Ask me ONE guiding question at a time, wait for my answer, and adapt to my confusion — build the idea with me step by step instead of explaining it all at once. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧪 Quiz me & fix my gaps

Active recall exposes what you missed.

Quiz me on **Command Pattern** with 5 questions, easy to tricky, ONE at a time. Tell me if each answer is right; at the end, explain clearly what I got wrong and why. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧠 Make it stick

Intuition + hook + flashcards for long-term memory.

Help me remember **Command Pattern** for the long term: give the one-sentence intuition, a memorable hook/mnemonic, a tiny worked example, and 3 active-recall flashcards (Q -> A). If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.

📝 My notes