38 lines
1.7 KiB
Python
38 lines
1.7 KiB
Python
|
from abc import ABC, abstractmethod
|
||
|
class Command(ABC):
|
||
|
@abstractmethod
|
||
|
def execute(self): pass
|
||
|
# Команда для включения света
|
||
|
class LightOnCommand(Command):
|
||
|
def __init__(self, light): self.light = light
|
||
|
def execute(self): self.light.turn_on()
|
||
|
# Команда для выключения света
|
||
|
class LightOffCommand(Command):
|
||
|
def __init__(self, light): self.light = light
|
||
|
def execute(self): self.light.turn_off()
|
||
|
# Класс, представляющий источник света (получатель комманд)
|
||
|
class Light:
|
||
|
def turn_on(self): print("Свет включен.")
|
||
|
def turn_off(self): print("Свет выключен.")
|
||
|
# Класс-отправитель (Invoker), который инициирует команды
|
||
|
class RemoteControl:
|
||
|
def __init__(self): self.commands = []
|
||
|
def set_command(self, command): self.commands.append(command)
|
||
|
def press_button(self):
|
||
|
if self.commands:
|
||
|
command = self.commands.pop(0) # Извлекаем и выполняем первую команду
|
||
|
command.execute()
|
||
|
else: print("Нет доступных команд.")
|
||
|
|
||
|
light = Light()
|
||
|
light_on, light_off = LightOnCommand(light), LightOffCommand(light) # Создаем команды
|
||
|
# Создаем пульт управления (invoker, который инициирует команды)
|
||
|
remote = RemoteControl()
|
||
|
# Устанавливаем команды
|
||
|
remote.set_command(light_on)
|
||
|
remote.set_command(light_off)
|
||
|
# Выполнение установленных команд
|
||
|
remote.press_button() # Включает свет
|
||
|
remote.press_button() # Выключает свет
|
||
|
remote.press_button() # Нет доступных команд
|