- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStateTest.java
More file actions
Latest commit
67 lines (51 loc) · 1.33 KB
/
Copy pathStateTest.java
File metadata and controls
67 lines (51 loc) · 1.33 KB
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
packageJavaPatternDemos;
/**
* State
* 状态的具体动作被隐藏,
* 状态的改变通常是非人为的
*
* 下面实现红蓝两种状态相互转化,可以更加复杂,感觉还是很实用的,
*
* 特别对于状态优先,状态之间转化关系明确的情况
*/
publicclassStateTest {
publicstaticvoidmain(String[] args) {
Contextcont = newContext(newStateBlue());
for (inti = 0; i <5 ; i++) {
cont.operate();
}
}
}
classContext {
privateStatestate = null;
publicContext(Stateinit_state){
state = init_state;
}
publicvoidoperate(){
state.handler_state(this);
}
publicvoidsetState(StatenewState){
this.state = newState;
}
}
abstractclassState{
publicabstractvoidhandler_state(Contextcont);
}
classStateBlueextendsState{
@Override
publicvoidhandler_state(Contextcont) {
// od something and change
System.out.println("this is state blue");
StatenextState = newStateRed();
cont.setState(nextState);
}
}
classStateRedextendsState{
@Override
publicvoidhandler_state(Contextcont) {
System.out.println("this is stae red");
// do somthing
StatenexState = newStateBlue();
cont.setState(nexState);
}
}