Repository navigation
Expand file tree
/
Copy pathcommand.py
More file actions
37 lines (36 loc) · 1.74 KB
/
Copy pathcommand.py
File metadata and controls
37 lines (36 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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() # Нет доступных команд