Команда (Command, Action, Transaction) — паттерн поведения объектов. Инкапсулирует запрос как объект, позволяя тем самым задавать параметры клиентов для обработки соответствующих запросов, ставить запросы в очередь или протоколировать их, а также поддерживать отмену операций.
class Light: def turn_on(self): print("Turn on") def turn_off(self): print("Tyrn off") class BaseCommand: def execute(self): raise NotImplementedError class BaseLigthCommand(BaseCommand): def __init__(self, light): self.light = light class TurnOnCommand(BaseLigthCommand): def execute(self): self.light.turn_on() class TurnOffCommand(BaseLigthCommand): def execute(self): self.light.turn_off() class Switch: def __init__(self, on_cmd, off_cmd): self.on_cmd = on_cmd self.off_cmd = off_cmd def on(self): self.on_cmd.execute() def off(self): self.off_cmd.execute() light = Light() switch = Switch(on_cmd=TurnOnCommand(light), off_cmd=TurnOffCommand(light)) switch.on() switch.off()
В результате получим
Turn on Tyrn off