Middle+
What is the 'Command' pattern?
sobes.tech AI
Answer from AI
The "Command" pattern is a behavioral design pattern that transforms a request into a standalone object containing all the information about the request. This transformation allows:
- Parameterizing client objects with different requests
- Queuing requests or logging them
- Supporting undo operations
Main participants of the pattern:
- Command: Declares an interface for executing an operation.
- Concrete Command: Implements the
Commandinterface and defines the binding between the receiver and the action. Executes the action by calling methods on the receiver. - Receiver: The class that knows how to perform the necessary actions.
- Invoker: The object that requests the execution of a command. It does not know anything about the specific command or receiver.
# Command interface
class Command:
def execute(self):
pass
# Concrete command
class ConcreteCommand(Command):
def __init__(self, receiver, argument):
self._receiver = receiver # Receiver
self._argument = argument
def execute(self):
self._receiver.action(self._argument)
# Receiver
class Receiver:
def action(self, arg):
print(f"Action executed with argument: {arg}")
# Invoker
class Invoker:
def set_command(self, command):
self._command = command
def execute_command(self):
self._command.execute()
# Example usage
receiver = Receiver()
command = ConcreteCommand(receiver, "Hello, Command!")
invoker = Invoker()
invoker.set_command(command)
invoker.execute_command()
The "Command" pattern is useful when:
- Deferred execution of operations: Ability to execute commands in the future.
- Command queues: Building a sequence of commands for execution.
- Undo operations: Saving the state of commands for undoing.
- Logging operations: Recording the history of executed commands.