-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommand_remote_control_easy_example.dart
96 lines (77 loc) · 2.05 KB
/
command_remote_control_easy_example.dart
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
92
93
94
95
96
/// src: https://github.com/scottt2/design-patterns-in-dart/blob/master/command/command.dart
abstract class Receiver {
Set<String> get actions;
}
abstract class Command {
late Receiver receiver;
late String name;
Command(this.receiver);
@override
String toString() => this.name;
void execute();
}
class Invoker {
List<String> history = [];
void execute(Command cmd) {
cmd.execute();
history.add("[${DateTime.now()}] Executed $cmd");
}
@override
String toString() =>
history.fold("", (events, event) => events + "$event\r\n");
}
class TurnOffCommand extends Command {
String name = "Turn off";
TurnOffCommand(Light light) : super(light);
void execute() {
(receiver as Light).turnOff();
}
}
class TurnOnCommand extends Command {
String name = "Turn on";
TurnOnCommand(Light light) : super(light);
void execute() {
(receiver as Light).turnOn();
}
}
class Light implements Receiver {
void turnOff() => print("Light off!");
void turnOn() => print("Light on!");
Set<String> get actions => Set.from(["off", "on"]);
}
class LightSwitch {
Invoker _switch = Invoker();
Light light;
LightSwitch(this.light);
String get history => _switch.toString();
void perform(String action) {
if (!light.actions.contains(action)) {
return print("Uh...wait, wut?");
}
switch (action) {
case "on":
return _switch.execute(TurnOnCommand(light));
case "off":
return _switch.execute(TurnOffCommand(light));
}
}
}
void main() {
var myFavoriteLamp = Light();
var iotLightSwitch = LightSwitch(myFavoriteLamp);
iotLightSwitch.perform("on");
iotLightSwitch.perform("off");
iotLightSwitch.perform("blink");
iotLightSwitch.perform("on");
print("\r\n*** Fancy IoT Switch Logs ***\r\n${iotLightSwitch.history}");
/*
Light on!
Light off!
Uh...wait, wut?
Light on!
*** Fancy IoT Switch Logs ***
[2019-06-20 08:00:38.880050] Executed Turn on
[2019-06-20 08:00:38.883495] Executed Turn off
[2019-06-20 08:00:38.883702] Executed Turn on
*/
}