Skip to content

Commit 038e3af

Browse files
committed
Add three_state project.
1 parent 080323d commit 038e3af

File tree

6 files changed

+76
-0
lines changed

6 files changed

+76
-0
lines changed
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import 'pattern/switcher.dart';
2+
import 'states/one.dart';
3+
4+
void main() {
5+
final switcher = Switcher(
6+
initState: One(),
7+
);
8+
9+
switcher.call(); // call(1): One
10+
switcher.call(); // call(2): Two
11+
switcher.call(); // call(3): Three
12+
switcher.call(); // call:(4) One
13+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
part of switcher;
2+
3+
abstract class State {
4+
Switcher get context => _context;
5+
6+
void call();
7+
8+
late Switcher _context;
9+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
library switcher;
2+
3+
part 'state.dart';
4+
5+
class Switcher {
6+
Switcher({required State initState}) {
7+
changeState(initState);
8+
}
9+
10+
int get calls => _calls;
11+
12+
void call() {
13+
_calls++;
14+
_state.call();
15+
}
16+
17+
void changeState(State newState) {
18+
_state = newState;
19+
_state._context = this;
20+
}
21+
22+
late State _state;
23+
int _calls = 0;
24+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import '../pattern/switcher.dart';
2+
import 'two.dart';
3+
4+
class One extends State {
5+
@override
6+
void call() {
7+
print('call(${context.calls}): One');
8+
context.changeState(Two());
9+
}
10+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import '../pattern/switcher.dart';
2+
import 'one.dart';
3+
4+
class Three extends State {
5+
@override
6+
void call() {
7+
print('call(${context.calls}): Three');
8+
context.changeState(One());
9+
}
10+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import '../pattern/switcher.dart';
2+
import 'three.dart';
3+
4+
class Two extends State {
5+
@override
6+
void call() {
7+
print('call(${context.calls}): Two');
8+
context.changeState(Three());
9+
}
10+
}

0 commit comments

Comments
 (0)