0
votes

I am atempting to implement (using Java) a Finite State machines and I'm stuck with the following issue

My requirements are that I have a system that needs to cycle through a set of known states

e.g. S1 -> S2 -> S3 ... SN -> S1

then stop once it has returned to its initial state.

The issue is that the initial state can be any of the known states e.g. S1 to SN (and out of my control)

Whichever state starts the cycle I need to ensure all other states are "visited" in the correct sequence before returning to whatever the initial state was

I wished to employ an Enum as follows:-

https://www.mirkosertic.de/blog/2013/04/implementing-state-machines-with-java-enums/

public enum State {

    INITIAL {
        @Override
        State doSomething(final String aParameter) {
            System.out.println("Doing Something in INITIAL state and jumping to NEXT_STEP, argument = " + aParameter);
            return NEXT_STEP;
        }
    },
    NEXT_STEP {
        @Override
        State doSomething(final String aParameter) {
            System.out.println("Doing Something in NEXT_STEP and jumping into FINAL, argument = " + aParameter);
            return FINAL;
        }
    },
    FINAL {
        @Override
        State doSomething(final String aParameter) {
            System.out.println("I am in FINAL state, argument = " + aParameter);
            return this;
        }
    };

    abstract State doSomething(String aParameter);

}

How can I achieve a cyclic FSM?

1

1 Answers

1
votes
  • Create one enum value per state.
  • Return the next state in doSomething.
  • Start with some state and cycle with doSomething until you reach it again.

Practically this will be something like:

public enum State {

    S1 {
        @Override
        State doSomething() {
            // Do something useful
            return S2;
        }
    },
    S2 {
        @Override
        State doSomething() {
            // Do something useful
            return S3;
        }
    },
    // ...
    SN {
        @Override
        State doSomething() {
            // Do something useful
            return S1;
        }
    },
    abstract State doSomething();
}

Then:

State state = initialState;
do {
    // Do something useful with state
}
while((state = initialState.doSomething()) != initialState);

To be honest I wouldn't be a big fan of implementing the FSM with enums as you planned above as it makes FSM pretty much hardcoded in the enum.