-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaction_example.dart
88 lines (66 loc) · 1.8 KB
/
action_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
import 'dart:io';
/// Step 1: Create an interface.
abstract interface class State {
void doAction(Context context);
}
/// Step 2: Create concrete classes implementing the same interface.
class StartState implements State {
@override
void doAction(Context context) {
print("Player is in start state");
context.setState(this);
}
@override
String toString() => "Start State";
}
class StopState implements State {
@override
void doAction(Context context) {
print("Player is in stop state");
context.setState(this);
}
@override
String toString() => "Stop State";
}
/// Step 3: Create Context Class.
class Context {
late State _state;
Context() : _state = StartState();
void setState(State state) => _state = state;
State get state => _state;
void doAction() {
_state.doAction(this);
}
}
/// Step 4: Use the Context to see change in behavior when State changes.
void main() {
Context context = Context();
final StartState startState = StartState();
startState.doAction(context);
print(context.state.toString());
final StopState stopState = StopState();
stopState.doAction(context);
print(context.state.toString());
/// Do While
while (true) {
print("\n");
print("Enter Operation: start - stop");
final String? op = stdin.readLineSync()?.toLowerCase().trim();
print("Now: The player is ${context.state}.");
if (op?.contains('start') == true) {
startState.doAction(context);
} else if (op?.contains('stop') == true) {
stopState.doAction(context);
} else {
print("Invalid operation. Please try again.");
break;
}
print("Done: The player is ${context.state}.");
print("\n");
}
}
/// Step 5: Verify the output.
// Player is in start state
// Start State
// Player is in stop state
// Stop State