-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathcommandpattern.py
76 lines (56 loc) · 1.6 KB
/
commandpattern.py
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
from abc import ABC, abstractmethod
class ICommand(ABC):
@abstractmethod
def execute(self):
pass
@abstractmethod
def undo(self):
pass
class TurnACOnCommand(ICommand):
def __init__(self, ac):
self.ac = ac
def execute(self):
self.ac.turn_on_AC()
def undo(self):
self.ac.turn_off_AC()
class TurnACOffCommand(ICommand):
def __init__(self, ac):
self.ac = ac
def execute(self):
self.ac.turn_off_AC()
def undo(self):
self.ac.turn_on_AC()
class MyRemoteControl:
command = None
AC_command_history = []
def set_command(self, command):
self.command = command
def press_button(self):
self.command.execute()
self.AC_command_history.append(self.command)
def undo(self):
if len(self.AC_command_history):
last_command = self.AC_command_history.pop()
last_command.undo()
class AirConditioner:
is_on = False
temperature = 0
def turn_on_AC(self):
self.is_on = True
print('AC is ON')
def turn_off_AC(self):
self.is_on = False
print('AC is OFF')
def set_temperature(self, temperature):
self.temperature = temperature
print('Temperature changed to:', self.temperature)
if __name__ == '__main__':
# AC object
air_conditioner = AirConditioner()
# remote
remote = MyRemoteControl()
# create command and press button
remote.set_command(TurnACOnCommand(air_conditioner))
remote.press_button()
# undo the last operation
remote.undo()