Designing a chain of states
Posted
by devoured elysium
on Stack Overflow
See other posts from Stack Overflow
or by devoured elysium
Published on 2010-04-26T09:51:33Z
Indexed on
2010/04/26
9:53 UTC
Read the original article
Hit count: 221
I want to model a kind of FSM(Finite State Machine). I have a sequence of states (let's say, from StateA to StateZ). This sequence is called a Chain and is implemented internally as a List. I will add states by the order I want them to run.
My purpose is to be able to make a sequence of actions in my computer (for example, mouse clicks). (I know this has been done a zillion times).
So a state is defined as a:
boolean Precondition()
<- Checks to see if for this state, some condition is true. For example, if I want to click in the Record button of a program, in this method I would check if the program's process is running or not. If it is, go to the next state in the chain list, otherwise, go to what was defined as the fail state (generally is the first state of them all).IState GetNextState()
<- Returns the next state to evaluate. If Precondition() was sucessful, it should yield the next state in the chain otherwise it should yield the fail state.Run()
Simply checks thePrecondition()
and sets the internal data soGetNextState()
works as expected.
So, a naive approach to this would be something like this:
Chain chain = new Chain();
//chain.AddState(new State(Precondition, FailState, NextState) <- Method structure
chain.AddState(new State(new WinampIsOpenCondition(), null, new <problem here, I want to referr to a state that still wasn't defined!>);
The big problem is that I want to make a reference to a State that at this point still wasn't defined. I could circumvent the problem by using strings when refrering to states and using an internal hashtable, but isn't there a clearer alternative?
I could just pass only the pre-condition and failure states in the constructor, having the chain just before execution put in each state the correct next state in a public property but that seems kind of awkward.
© Stack Overflow or respective owner