Command Pattern¶
Category: Behavioral Pattern
Overview¶
Encapsulate a request as an object, thereby allowing for parameterization of clients with queues, requests, and operations. This pattern supports undoable operations, request logging, and transaction management by turning requests into stand-alone objects.
Usage Guidelines¶
Use when:
- Need to parameterize objects with operations
- Operations need to be queued for later execution
- Need to support undoable operations
- Operations must be logged for audit or recovery
Avoid when:
- Direct method calls are sufficient for simple operations
- No need for undo, logging, or queueing
- Command object overhead is unacceptable for performance
- Only one type of operation exists
Implementation¶
from __future__ import annotations
from abc import ABC, abstractmethod
class Light:
"""Receiver: the object a command acts on."""
def __init__(self) -> None:
self.is_on = False
def turn_on(self) -> str:
self.is_on = True
return "Light is on"
def turn_off(self) -> str:
self.is_on = False
return "Light is off"
class Command(ABC):
"""Interface every command implements: do the action, and reverse it."""
@abstractmethod
def execute(self) -> str:
"""Perform the action and describe what happened."""
@abstractmethod
def undo(self) -> str:
"""Reverse the action and describe what happened."""
class LightOnCommand(Command):
"""Command to turn a light on; undo turns it off again."""
def __init__(self, light: Light) -> None:
self._light = light
def execute(self) -> str:
return self._light.turn_on()
def undo(self) -> str:
return self._light.turn_off()
class LightOffCommand(Command):
"""Command to turn a light off; undo turns it on again."""
def __init__(self, light: Light) -> None:
self._light = light
def execute(self) -> str:
return self._light.turn_off()
def undo(self) -> str:
return self._light.turn_on()
class RemoteControl:
"""Invoker: queues commands, runs them, and can undo the last one run."""
def __init__(self) -> None:
self.commands: list[Command] = []
self._history: list[Command] = []
def add_command(self, command: Command) -> None:
self.commands.append(command)
def execute_commands(self) -> list[str]:
results = [command.execute() for command in self.commands]
self._history.extend(self.commands)
self.commands.clear()
return results
def undo_last(self) -> str:
if not self._history:
return "Nothing to undo"
return self._history.pop().undo()
Usage¶
light = Light()
remote = RemoteControl()
remote.add_command(LightOnCommand(light))
remote.add_command(LightOffCommand(light))
remote.add_command(LightOnCommand(light))
print(remote.execute_commands()) # ["Light is on", "Light is off", "Light is on"]
print(light.is_on) # True
print(remote.undo_last()) # "Light is off"
print(light.is_on) # False
print(remote.undo_last()) # "Light is on"
print(remote.undo_last()) # "Light is off"
print(remote.undo_last()) # "Nothing to undo"
The invoker never touches the light; it only knows that a command can be executed and undone. The receiver keeps the state, the command records how to change it and how to change it back, and the history in the invoker turns that into undo.
Trade-offs¶
Benefits:
- Decouples sender from receiver of requests
- Easy to add new commands without changing existing code
- Commands can be composed into macro commands
- Supports undo and redo functionality
Drawbacks:
- Creates many command classes increasing code volume
- Adds complexity for simple operations
- Storing commands consumes memory
- Extra layer of indirection can impact performance
Real-World Examples¶
- GUI buttons and menu items with each action as a command
- Text editors with undo/redo functionality
- Transaction systems with database transactions and rollback
- Job schedulers queueing jobs for execution
Related Patterns¶
- Memento
- Prototype
- Composite
- Chain of Responsibility
- Strategy
API Reference¶
design_patterns.behavioral.command
¶
Command Pattern Module
This module implements the Command design pattern, which encapsulates a
request as an object. A receiver (Light) holds the state, each command
records how to change it and how to change it back, and an invoker
(RemoteControl) queues commands, runs them, and can undo the last one run.
Example
Command
¶
Bases: ABC
Interface every command implements: do the action, and reverse it.
Source code in src/design_patterns/behavioral/command.py
Light
¶
Receiver: the object commands act on.
Source code in src/design_patterns/behavioral/command.py
LightOffCommand
¶
Bases: Command
Command to turn a light off; undo turns it on again.
Source code in src/design_patterns/behavioral/command.py
__init__(light)
¶
Bind the command to the light it controls.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
light
|
Light
|
The receiver. |
required |
execute()
¶
Turn the light off.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The receiver's description of its new state. |
undo()
¶
Turn the light on again.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The receiver's description of its new state. |
LightOnCommand
¶
Bases: Command
Command to turn a light on; undo turns it off again.
Source code in src/design_patterns/behavioral/command.py
__init__(light)
¶
Bind the command to the light it controls.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
light
|
Light
|
The receiver. |
required |
execute()
¶
Turn the light on.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The receiver's description of its new state. |
undo()
¶
Turn the light off again.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The receiver's description of its new state. |
RemoteControl
¶
Invoker: queues commands, runs them, and can undo the last one run.
Source code in src/design_patterns/behavioral/command.py
__init__()
¶
add_command(command)
¶
Queue a command for the next execution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
command
|
Command
|
The command to add. |
required |
execute_commands()
¶
Run every queued command in order and remember it for undo.
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: Each command's description of what it did. |
Source code in src/design_patterns/behavioral/command.py
undo_last()
¶
Reverse the most recently executed command.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The command's description of the reversal, or a message saying there was nothing to undo. |