forked from BruceEckel/OnJava8-Examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStateMachineDemo.java
More file actions
80 lines (72 loc) · 1.58 KB
/
StateMachineDemo.java
File metadata and controls
80 lines (72 loc) · 1.58 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// patterns/state/StateMachineDemo.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// The StateMachine pattern and Template method
// {java patterns.state.StateMachineDemo}
package patterns.state;
import onjava.Nap;
interface State {
void run();
}
abstract class StateMachine {
protected State currentState;
protected abstract boolean changeState();
// Template method:
protected final void runAll() {
while(changeState()) // Customizable
currentState.run();
}
}
// A different subclass for each state:
class Wash implements State {
@Override
public void run() {
System.out.println("Washing");
new Nap(0.5);
}
}
class Spin implements State {
@Override
public void run() {
System.out.println("Spinning");
new Nap(0.5);
}
}
class Rinse implements State {
@Override
public void run() {
System.out.println("Rinsing");
new Nap(0.5);
}
}
class Washer extends StateMachine {
private int i = 0;
// The state table:
private State[] states = {
new Wash(), new Spin(),
new Rinse(), new Spin(),
};
Washer() { runAll(); }
@Override
public boolean changeState() {
if(i < states.length) {
// Change the state by setting the
// surrogate reference to a new object:
currentState = states[i++];
return true;
} else
return false;
}
}
public class StateMachineDemo {
public static void main(String[] args) {
new Washer();
}
}
/* Output:
Washing
Spinning
Rinsing
Spinning
*/