Squeak
  links to this page:    
View this PageEdit this PageUploads to this PageHistory of this PageTop of the SwikiRecent ChangesSearch the SwikiHelp Guide
Java/Smalltalk State machine examples
Last updated at 12:52 am UTC on 17 January 2006
Following is an example of how state machines are commonly implemented in Java. As you can see its pretty simple and very procedural. It does have the advantage that its very readable and efficient.


public class StateTest extends Object
{
private static final byte START_STATE = 1;
private static final byte SEC_STATE = 2;
private static final byte THIRD_STATE = 3;
private static final byte FOURTH_STATE = 4;

private byte curState = START_STATE;


public void doIt()
{
switch(_curState)
{
case START_STATE:
// do some stuff
this.curState = SEC_STATE;
break;
case SEC_STATE:
// do some stuff
this.curState = THIRD_STATE;
break;
case THIRD_STATE:
// do some stuff
this.curState = FOURTH_STATE;
break;
case FOURTH_STATE:
//do some stuff
this.curState = START_STATE;
break;
default:
//signal error
}
}
}



A similar example ins smalltalk would be

Object subclass: #StateTest
instanceVariableNames: 'state'
classVariableNames: ''
poolDictionaries: ''
category: 'State-Test'

initialize
"Initiazes the state var"
state _ #startState

doIt
"Does something in a statefull manner"
self perform: state

startState
"Do somthing usefull"
state _ #secState

secState
"Do something usefull"
state _ #thirdState

thirdState
"Do something usefull"
state _ #fourthState

fourthState
"Do somethingusefull"
state _ #startState