Has anyone tried making a state pattern in their code?
I’ve got some normal state machines that need re-coding using the design pattern approach. I’ve no experience with this technique but have managed to follow a book and construct something that compiles but won’t run (an unfortunate case in which constructing the Actions requires the object to send it self to itself causing a bit of an infinite loop).
Oh great, thank you. Here is a cut down of the code I’ve made. I’ve been following a Java written book which has got me this far (it compiles) but won’t run.
As I understand the technique, my state pattern [StatePattenClass] is a subclass of my main class [MyMainClass] (so I can access the main class’s boolean for example). This class has the various events as member functions and a constructor which sets up the various states. These states are created as further sub-classes of the main state patten class so inherit all the event functions. I then populate these functions with the statements to make the state machine work.
The problem I have is that when the constructor is called, it calls the constructors of each state class, which send ‘this’ as the argument (according to the book) which causes the infinite constructing loop.
// CODE:
public class StatePattenClass : MyMainClass {
static public StatePattenClass Active;
// OTHER STATES HERE
StatePattenClass currentstate = Active;
public StatePattenClass() { // CONSTRUCTOR
Active = new Active(this);
}
public void EventFunction() {
currentstate.EventFunction();
}
// OTHER EVENTS HERE
public void SetState(StatePattenClass state) {
this.currentstate = state;
}
}
class Active : StatePattenClass {
public Active(StatePattenClass state) {
state = this;
}
public void EventFunction() {
SetState(Active); // remain Active
}
}
Thank you for updating the code for me, I forgot to work out how to post as code.
I already have a state machine working using switch statements, but it seems that the state pattern method is more readable and future update-able (which is important to us). Quite a few of our state machines are pretty complicated and getting them to be correct & exhaustive with switch statements is no simple task.