-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand_pattern.py
More file actions
91 lines (66 loc) · 1.83 KB
/
command_pattern.py
File metadata and controls
91 lines (66 loc) · 1.83 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
from abc import *
class Command(ABC):
@abstractmethod
def execute(self) -> None: ...
class Light:
def __init__(self):
self.on = False
def turn_on(self):
self.on = True
print("Light turned on")
def turn_off(self):
self.on = False
print("Light turned off")
class TV:
def __init__(self):
self.on = False
def turn_on(self):
self.on = True
print("TV turned on")
def turn_off(self):
self.on = False
print("TV turned off")
class LightOnCommand(Command):
def __init__(self, light: Light):
self.light = light
def execute(self):
self.light.turn_on()
class LightOffCommand(Command):
def __init__(self, light: Light):
self.light = light
def execute(self):
self.light.turn_off()
class TVOnCommand(Command):
def __init__(self, tv: TV):
self.tv = tv
def execute(self):
self.tv.turn_on()
class TVOffCommand(Command):
def __init__(self, tv: TV):
self.tv = tv
def execute(self):
self.tv.turn_off()
class RemoteControl:
def __init__(self):
self.command = None
def set_command(self, command: Command):
self.command = command
def press_button(self):
if self.command:
self.command.execute()
if __name__ == '__main__':
light = Light()
tv = TV()
light_on = LightOnCommand(light)
light_off = LightOffCommand(light)
tv_on = TVOnCommand(tv)
tv_off = TVOffCommand(tv)
remote = RemoteControl()
remote.set_command(light_on)
remote.press_button()
remote.set_command(tv_on)
remote.press_button()
remote.set_command(light_off)
remote.press_button()
remote.set_command(tv_off)
remote.press_button()