Main Site Documentation

State Machine Pattern - Experience Wanted


#1

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).

I can provide code if this would help anyone.

Nick


#2

The state pattern is not hard to make.
Show us what you got, maybe we will find the error quickly.


#3

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
  }
}

#4

I am not sure what you exactly need but if I was doing state-machine then I would just do it using a “switch-case”

I modified your post to include code tags so it is easy to read


#5

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.


#6

I might have meant ‘Design Pattern’.

The book I’m following is "Head First Design Patterns"


#7

http://www.blackwasp.co.uk/State.aspx

This website gives a good generic code structure and then a clear example implementation of the State Pattern.

It now works :slight_smile: