0
0
LldConceptBeginner · 3 min read

Command Pattern: Definition, Example, and Use Cases

The Command Pattern is a design pattern that turns a request into a stand-alone object containing all information about the action. This allows you to parameterize methods with different requests, queue or log requests, and support undoable operations.
⚙️

How It Works

Imagine you want to control a remote device, like a TV, but you want to keep the remote and the TV separate. The Command Pattern acts like a remote control button that stores the action to perform, such as turning the TV on or off. Instead of the remote knowing how to do the action, it just holds a command object that knows exactly what to do.

This pattern wraps a request as an object, so you can pass it around, store it, or execute it later. It separates the object that asks for an action from the one that performs it. This makes your code flexible and easy to extend.

💻

Example

This example shows a simple light switch system where commands turn the light on or off. The switch holds commands and executes them without knowing the details.
python
from abc import ABC, abstractmethod

# Command interface
class Command(ABC):
    @abstractmethod
    def execute(self):
        pass

# Receiver
class Light:
    def on(self):
        print("Light is ON")
    def off(self):
        print("Light is OFF")

# Concrete Commands
class LightOnCommand(Command):
    def __init__(self, light):
        self.light = light
    def execute(self):
        self.light.on()

class LightOffCommand(Command):
    def __init__(self, light):
        self.light = light
    def execute(self):
        self.light.off()

# Invoker
class RemoteControl:
    def __init__(self):
        self.command = None
    def set_command(self, command):
        self.command = command
    def press_button(self):
        if self.command:
            self.command.execute()

# Client code
light = Light()
remote = RemoteControl()

remote.set_command(LightOnCommand(light))
remote.press_button()  # Turns light on

remote.set_command(LightOffCommand(light))
remote.press_button()  # Turns light off
Output
Light is ON Light is OFF
🎯

When to Use

Use the Command Pattern when you want to:

  • Decouple the object that sends a request from the one that performs it.
  • Support undo and redo operations by storing commands.
  • Queue or log requests for later execution.
  • Implement callbacks or progress tracking.

For example, in a text editor, commands can represent typing, deleting, or formatting actions that can be undone or redone. In home automation, commands can represent turning devices on or off without the controller needing to know device details.

Key Points

  • The pattern encapsulates a request as an object.
  • It separates the sender and receiver of a request.
  • Commands can be stored, queued, or logged.
  • Supports undo/redo by keeping command history.
  • Improves flexibility and extensibility of code.

Key Takeaways

Command Pattern encapsulates actions as objects to separate requesters from executors.
It enables queuing, logging, and undoing operations easily.
Use it when you need flexible and extensible command handling.
Commands can be passed, stored, or executed later without changing the sender.
It improves code maintainability by decoupling components.