1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.xnap.util;
21
22 /***
23 * Provides an abstract state machine. Subclasses need to take care of the
24 * state transitions.
25 */
26 public abstract class AbstractStateMachine
27 {
28
29
30
31
32
33 private String description;
34 private State state;
35
36
37
38 public AbstractStateMachine(State initialState)
39 {
40 this.state = initialState;
41 }
42
43
44
45 public String getDescription()
46 {
47 return description;
48 }
49
50 public synchronized State getState()
51 {
52 return state;
53 }
54
55 public void setDescription(String description)
56 {
57 this.description = description;
58 }
59
60 /***
61 *
62 */
63 public synchronized void setState(State newState, String description)
64 {
65 canChange(state, newState);
66
67 State oldState = state;
68 state = newState;
69 setDescription((description != null)
70 ? description : state.getDescription());
71
72 stateChanged(oldState, newState);
73 }
74
75 public synchronized void setState(State newState)
76 {
77 setState(newState, null);
78 }
79
80 /***
81 * Invoked when a state transition is attempted. Should throw an
82 * exception if transistion is invalid.
83 */
84 protected abstract void canChange(State currentState, State newState);
85
86 /***
87 * Invoked when the state has changed.
88 */
89 protected abstract void stateChanged(State oldState, State newState);
90
91 }
92
93