View Javadoc

1   /*
2    *  XNap - A P2P framework and client.
3    *
4    *  See the file AUTHORS for copyright information.
5    *
6    *  This program is free software; you can redistribute it and/or modify
7    *  it under the terms of the GNU General Public License as published by
8    *  the Free Software Foundation.
9    *
10   *  This program is distributed in the hope that it will be useful,
11   *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12   *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   *  GNU General Public License for more details.
14   *
15   *  You should have received a copy of the GNU General Public License
16   *  along with this program; if not, write to the Free Software
17   *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
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      //--- Constant(s) ---
30  
31      //--- Data field(s) ---
32  
33      private String description;
34      private State state;
35  
36      //--- Constructor(s) ---
37  
38      public AbstractStateMachine(State initialState)
39      {
40  		this.state = initialState;
41      }
42  
43      //--- Method(s) ---
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