Sobes.tech
Middle

What is the 'Command' pattern?

sobes.tech AI

Answer from AI

The behavioral design pattern that turns a request into a separate object containing all the information about the request. This allows parameterizing methods with different requests, queuing requests, logging them, and also supports undo operations.

Main elements of the pattern:

  • Command: An abstract class or interface declaring a method for executing the request.
    // Command interface
    class Command:
        def execute(self):
            pass
    
  • Concrete Command: Implements the Command interface and binds the receiver with an action. Defines a set of actions to be performed on the receiver.
    // Concrete command for turning on the light
    class LightOnCommand(Command):
        def __init__(self, light):
            self._light = light # Receiver
    
        def execute(self):
            self._light.on()
    
  • Receiver: The class that knows how to perform the actual work. In our example, it is Light.
    // Receiver - the object on which actions are performed
    class Light:
        def on(self):
            print("Light is on")
    
        def off(self):
            print("Light is off")
    
  • Invoker: The object that requests the command to perform an action. It does not know about the specific command or receiver.
    // Invoker - calls the command
    class RemoteControl:
        def set_command(self, command):
            self._command = command
    
        def press_button(self):
            self._command.execute()
    
  • Client: Creates Concrete Command objects and binds them with Receiver. Then passes the command to the Invoker.
    // Client code
    if __name__ == "__main__":
        light = Light() # Receiver
        light_on_command = LightOnCommand(light) # Concrete command
    
        remote = RemoteControl() # Invoker
        remote.set_command(light_on_command) # Passing command to invoker
    
        remote.press_button() # Invoker executes the command
    

Advantages:

  • Separates the invoker and receiver of the command.
  • Allows parameterizing the invoker with different commands.
  • Facilitates undo/redo operations (by saving command history).
  • Enables building command queues and logging their execution.

Disadvantages:

  • Can lead to a large number of classes if many commands are used.
What is the 'Command' pattern? — Python - sobes.tech