Python


class Light:
    def turn_on(self):
        print("")
   
    def turn_off(self):
        print("")

#
light = Light()
light.turn_on()
light.turn_off()

  1. /

python-command.png [python-command.png]

  • /

Command execute(), undo()
ConcreteCommand LightOnCommand, LightOffCommand
Receiver Light, TV
Invoker RemoteControl

from abc import ABC, abstractmethod
from typing import List

# 1.
class Command(ABC):
    @abstractmethod
    def execute(self):
        pass
   
    @abstractmethod
    def undo(self):
        pass

# 2. -
class Light:
    def turn_on(self):
        print("💡 ")
   
    def turn_off(self):
        print("💡 ")

# 3. -
class LightOnCommand(Command):
    def __init__(self, light: Light):
        self.light = light
   
    def execute(self):
        self.light.turn_on()
   
    def undo(self):
        self.light.turn_off()

# 4. -
class LightOffCommand(Command):
    def __init__(self, light: Light):
        self.light = light
   
    def execute(self):
        self.light.turn_off()
   
    def undo(self):
        self.light.turn_on()

# 5. -
class RemoteControl:
    def __init__(self):
        self.command = None
        self.history: List[Command] = []
   
    def set_command(self, command: Command):
        self.command = command
   
    def press_button(self):
        if self.command:
            self.command.execute()
            self.history.append(self.command)
   
    def press_undo(self):
        if self.history:
            last_command = self.history.pop()
            last_command.undo()

#
if __name__ == "__main__":
    #
    living_room_light = Light()
   
    #
    light_on = LightOnCommand(living_room_light)
    light_off = LightOffCommand(living_room_light)
   
    #
    remote = RemoteControl()
   
    #
    print("=== ===")
    remote.set_command(light_on)
    remote.press_button()
   
    #
    print("\n=== ===")
    remote.set_command(light_off)
    remote.press_button()
   
    #
    print("\n=== ===")
    remote.press_undo()  #
    remote.press_undo()  #

2f550c1b-d9ca-4d1a-b6e8-fd31a66fa0f5.png [2f550c1b-d9ca-4d1a-b6e8-fd31a66fa0f5.png]


# -
class TV:
    def __init__(self, location: str):
        self.location = location
        self.is_on = False
        self.volume = 50
   
    def turn_on(self):
        self.is_on = True
        print(f"📺 {self.location}")
   
    def turn_off(self):
        self.is_on = False
        print(f"📺 {self.location}")
   
    def set_volume(self, volume: int):
        self.volume = volume
        print(f"📺 {self.location} {volume}")

#
class TVOnCommand(Command):
    def __init__(self, tv: TV):
        self.tv = tv
        self.previous_volume = 50
   
    def execute(self):
        self.previous_volume = self.tv.volume
        self.tv.turn_on()
   
    def undo(self):
        self.tv.turn_off()
        self.tv.volume = self.previous_volume

class TVVolumeUpCommand(Command):
    def __init__(self, tv: TV):
        self.tv = tv
        self.previous_volume = 50
   
    def execute(self):
        self.previous_volume = self.tv.volume
        self.tv.set_volume(min(100, self.tv.volume + 10))
   
    def undo(self):
        self.tv.set_volume(self.previous_volume)

# -
class MacroCommand(Command):
    def __init__(self, commands: List[Command]):
        self.commands = commands
   
    def execute(self):
        for command in self.commands:
            command.execute()
   
    def undo(self):
        #
        for command in reversed(self.commands):
            command.undo()

#
class AdvancedRemoteControl:
    def __init__(self, slot_count: int = 4):
        self.on_commands: List[Command] = [None] * slot_count
        self.off_commands: List[Command] = [None] * slot_count
        self.history: List[Command] = []
   
    def set_command(self, slot: int, on_command: Command, off_command: Command):
        self.on_commands[slot] = on_command
        self.off_commands[slot] = off_command
   
    def press_on_button(self, slot: int):
        if self.on_commands[slot]:
            self.on_commands[slot].execute()
            self.history.append(self.on_commands[slot])
   
    def press_off_button(self, slot: int):
        if self.off_commands[slot]:
            self.off_commands[slot].execute()
            self.history.append(self.off_commands[slot])
   
    def press_undo(self):
        if self.history:
            last_command = self.history.pop()
            last_command.undo()

#
def test_advanced_remote():
    print("=== ===")
   
    #
    living_room_light = Light()
    bedroom_tv = TV("")
   
    #
    light_on = LightOnCommand(living_room_light)
    light_off = LightOffCommand(living_room_light)
    tv_on = TVOnCommand(bedroom_tv)
    tv_volume_up = TVVolumeUpCommand(bedroom_tv)
   
    # -
    cinema_mode = MacroCommand([light_off, tv_on, tv_volume_up])
   
    #
    remote = AdvancedRemoteControl()
    remote.set_command(0, light_on, light_off)      # 0
    remote.set_command(1, tv_on, TVOnCommand(bedroom_tv))  # 1
    remote.set_command(2, cinema_mode, light_on)    # 2
   
    #
    print("\n1. :")
    remote.press_on_button(0)
   
    print("\n2. :")
    remote.press_on_button(2)
   
    print("\n3. :")
    remote.press_undo()

if __name__ == "__main__":
    test_advanced_remote()

class AdvancedCommand(ABC):
    @abstractmethod
    def execute(self):
        """"""
        pass
   
    @abstractmethod
    def undo(self):
        """"""
        pass
   
    @abstractmethod
    def redo(self):
        """"""
        pass
   
    @abstractmethod
    def can_execute(self) -> bool:
        """"""
        pass
   
    @abstractmethod
    def get_description(self) -> str:
        """"""
        pass

class CommandQueue:
    def __init__(self):
        self.queue: List[Command] = []
   
    def add_command(self, command: Command):
        self.queue.append(command)
   
    def process_commands(self):
        while self.queue:
            command = self.queue.pop(0)
            if command.can_execute():
                command.execute()
   
    def clear(self):
        self.queue.clear()

1

#
class AirConditioner:
    def __init__(self):
        self.temperature = 26
        self.is_on = False
   
    def turn_on(self):
        #
        pass
   
    def turn_off(self):
        #
        pass
   
    def set_temperature(self, temp: int):
        #
        pass

#
# AirConditionerOnCommand
# AirConditionerOffCommand  
# TemperatureUpCommand
# TemperatureDownCommand

2

class TextEditor:
    def __init__(self):
        self.content = ""
   
    def add_text(self, text: str):
        #
        pass
   
    def delete_text(self, length: int):
        #
        pass

#
# AddTextCommand
# DeleteTextCommand

Q:

A:

  • /

Q:

A:

Q:

A:

  • /

/

  • """"
  • GUI