-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcommand_pattern.py
81 lines (53 loc) · 1.38 KB
/
command_pattern.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
77
78
"""
from
https://en.wikipedia.org/wiki/Command_pattern#Python
"""
# invoker, command, receiver, client
class Switch:
"""invoker"""
def __init__(self):
self._history = ()
@property
def history(self):
return self._history
def execute(self, command):
self._history += (command,)
command.execute()
class Command:
"""Command interface"""
def __init__(self, obj):
self._obj = obj
def execute(self):
raise NotImplementedError
class TurnOnCommand(Command):
def execute(self):
self._obj.turn_on()
class TurnOffCommand(Command):
def execute(self):
self._obj.turn_off()
class Light:
def turn_on(self):
print('light on')
def turn_off(self):
print('light off')
class LightSwitchRemote:
def __init__(self):
self._lamp = Light()
self._switch= Switch()
@property
def history(self):
return self._switch.history
def pressed(self, cmd):
cmd = cmd.strip().upper()
if cmd == 'ON':
self._switch.execute(TurnOnCommand(self._lamp))
elif cmd == 'OFF':
self._switch.execute(TurnOffCommand(self._lamp))
else:
print('on or off')
remote = LightSwitchRemote()
remote.pressed('on')
remote.pressed('off')
remote.pressed('offsfadsfsaf')
remote.pressed('on')
print(remote.history)