-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstatus_example.dart
78 lines (63 loc) · 1.7 KB
/
status_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
// ignore_for_file: unnecessary_getters_setters
import 'dart:io';
abstract class State {
void handler(Stateful context);
@override
String toString();
}
class StatusOn implements State {
@override
void handler(Stateful context) {
print(" Handler of StatusOn is being called!");
context.state = StatusOff();
}
@override
String toString() => "on";
}
class StatusOff implements State {
@override
void handler(Stateful context) {
print(" Handler of StatusOff is being called!");
context.state = StatusOn();
}
@override
String toString() => "off";
}
class Stateful {
State _state;
Stateful(this._state);
State get state => _state;
set state(State newState) => _state = newState;
void touch() {
print(" Touching the Stateful...");
_state.handler(this);
}
}
void main() {
final offState = StatusOff();
final onState = StatusOn();
var lightSwitch = Stateful(offState);
// Normal Operation
print("The light switch is ${lightSwitch.state}.");
print("Toggling the light switch...");
lightSwitch.touch();
print("The light switch is ${lightSwitch.state}.");
while (true) {
print("Enter Operation: on - off");
final String? op = stdin.readLineSync()?.toLowerCase().trim();
print("Now: The light switch is ${lightSwitch.state}.");
if (op?.contains('on') == true) {
lightSwitch.state = onState;
lightSwitch.touch();
} else if (op?.contains('off') == true) {
lightSwitch.state = offState;
lightSwitch.touch();
} else {
print("Invalid operation. Please try again.");
break;
}
print("Toggling the light switch...");
print("The light switch is ${lightSwitch.state}.");
print("\n");
}
}