Skip to content

Commit e5d52f6

Browse files
committed
Command pattern definition
1 parent 2ddfdba commit e5d52f6

File tree

2 files changed

+22
-14
lines changed

2 files changed

+22
-14
lines changed

chapter06_command/readme.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Chapter 6: Command design pattern
2+
3+
> **Command**: Encapsulates a request as an object, thereby letting you parameterise clients with different requests, queue or log requests, and support undoable operations.

chapter06_command/remote_undo.py

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ def __init__(self, light):
2424
def execute(self):
2525
self.level = self.light.get_level()
2626
self.light.on()
27-
27+
2828
def undo(self):
2929
self.light.dim(self.level)
3030

@@ -36,13 +36,13 @@ def __init__(self, light):
3636
def execute(self):
3737
self.level = self.light.get_level()
3838
self.light.off()
39-
39+
4040
def undo(self):
4141
self.light.dim(self.level)
4242

4343

44-
class Light():
45-
def __init__(self, location:str):
44+
class Light:
45+
def __init__(self, location: str):
4646
self.location = location
4747
self.level = 0
4848

@@ -60,12 +60,12 @@ def dim(self, level):
6060
self.off()
6161
else:
6262
print(f"Light is dimmed to {self.level}%")
63-
63+
6464
def get_level(self):
6565
return self.level
6666

6767

68-
class RemoteControlWithUndo():
68+
class RemoteControlWithUndo:
6969
"""The Invoker"""
7070

7171
def __init__(self) -> None:
@@ -91,17 +91,21 @@ def undo_button_was_pushed(self):
9191
def __str__(self) -> str:
9292
buffer = []
9393
buffer.append("\n------ Remote Control -------\n")
94-
for i, (on_command, off_command) in enumerate(zip(self.on_commands, self.off_commands)):
95-
buffer.append(f"[slot {i}] {on_command.__class__.__name__}" +
96-
f" {off_command.__class__.__name__}\n")
97-
94+
for i, (on_command, off_command) in enumerate(
95+
zip(self.on_commands, self.off_commands)
96+
):
97+
buffer.append(
98+
f"[slot {i}] {on_command.__class__.__name__}"
99+
+ f" {off_command.__class__.__name__}\n"
100+
)
101+
98102
buffer.append(f"[undo] {self.undo_command.__class__.__name__}\n")
99103
return "".join(buffer)
100104

101105

102106
def remote_loader():
103-
remoteControl = RemoteControlWithUndo()
104-
living_room_light = Light("Living Room")
107+
remoteControl = RemoteControlWithUndo()
108+
living_room_light = Light("Living Room")
105109
living_room_light_on = LightOnCommand(living_room_light)
106110
living_room_light_off = LightOffCommand(living_room_light)
107111

@@ -116,5 +120,6 @@ def remote_loader():
116120
print(remoteControl)
117121
remoteControl.undo_button_was_pushed()
118122

119-
if __name__ == '__main__':
120-
remote_loader()
123+
124+
if __name__ == "__main__":
125+
remote_loader()

0 commit comments

Comments
 (0)