System Design ( Day - 51 )

Manoj KumarManoj Kumar
2 min read

Command Design Pattern

Definition
Encapsulate a request as an object, therby letting you parameterise clients with different request, queue or log request and support undoable operations.

🏑 Problem Statement

We want to build a Remote Control System that can:

  • Control multiple devices (like lights),

  • Allow easy command assignment,

  • Support undo operations.

🎯 Why the Command Pattern?

The Command Pattern turns a request into a standalone object containing all the information about the action. This helps in:

  • Decoupling the sender (Remote) from the receiver (Light),

  • Supporting features like undo/redo,

  • Making commands easily extendable for new devices.

🧱 The Components

πŸ“¦ ICommand (Command Interface)

Defines the structure with two key methods:

execute();
undo();

πŸ’‘ LightCommand (Concrete Command)

Wraps the Light device and implements what execute() and undo() do:

execute() β†’ light.on();
undo() β†’ light.off();

πŸ”Œ Light (Receiver)

Actual class that knows how to perform actions:

on() β†’ turns light on  
off() β†’ turns light off

πŸŽ› RemoteControl (Invoker)

  • Stores a list of commands.

  • Can dynamically assign commands using setCommand(index, cmd).

  • Executes them via pressButton(index).


πŸ“² How It Works Together

  1. You create a LightCommand with a Light object.

  2. The command is given to the RemoteControl.

  3. When a button is pressed, the remote doesn't care what the command is β€” it just calls execute().

  4. You can even call undo() to reverse the action!


πŸ”„ Benefits of This Approach

  • Loose coupling between remote and devices.

  • Easily extendable β€” Want to add a fan or AC? Just create a new command!

  • Undo support β€” Great for real-world use cases.

  • Cleaner code, respecting SOLID principles.

🧠 Final Thoughts

The Command Pattern shines in scenarios where you need decoupled and flexible control logic. It’s widely used in GUI systems, task queues, and, yes β€” smart homes.

This small system forms the foundation of larger IoT-based architectures. Try building on top of it β€” maybe add scheduling, voice control, or a mobile app interface!

Real World Examples

Text Editor or Photoshop or any of the application that uses the undo feature then we’ll use the Command design pattern. like whenever you are changing the text style like bold, italic or something else we can also use undo right, here we can use this Command design pattern.

0
Subscribe to my newsletter

Read articles from Manoj Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Manoj Kumar
Manoj Kumar