-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommand.py
67 lines (51 loc) · 1.33 KB
/
command.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
from abc import ABC, abstractmethod
# Receiver
class Light:
def turn_on(self):
print("The light is on")
def turn_off(self):
print("The light is off")
# Command Interface
class Command(ABC):
@abstractmethod
def execute(self):
pass
# Concrete Command for turning on the light
class LightOnCommand(Command):
def __init__(self, light):
self.light = light
def execute(self):
self.light.turn_on()
# Concrete Command for turning off the light
class LightOffCommand(Command):
def __init__(self, light):
self.light = light
def execute(self):
self.light.turn_off()
# Invoker
class RemoteControl:
def __init__(self):
self.command = None
def set_command(self, command):
self.command = command
def press_button(self):
self.command.execute()
# Client code
def client_code():
light = Light()
light_on = LightOnCommand(light)
light_off = LightOffCommand(light)
remote = RemoteControl()
remote.set_command(light_on)
print("Client: Turning the light on.")
remote.press_button()
remote.set_command(light_off)
print("Client: Turning the light off.")
remote.press_button()
# Usage
client_code()
## Output
# Client: Turning the light on.
# The light is on
# Client: Turning the light off.
# The light is off