Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

State Machine

State Machines are a model used in computing to define the current state of the system, and the possible next state which it may transition to.

These machines can only be in one state at any given time.

Enum State Machine

The purpose of implementing a state machine using Enums is so that the state doesn't have to be explicitly set.

...

Code Block
languagejava
titleState Machine Transition
linenumberstrue
public enum CmHandleState {

    Advised {
        @Override
        public CmHandleState nextState() {
            return Locked;
        }

        @Override
        public String cmHandleState() {
            return "ADVISED";
        }
    },
    Locked {
        @Override
        public CmHandleState nextState() {
            return Ready;
        }

        @Override
        public String cmHandleState() {
            return "LOCKED";
        }
    },
    Ready {
        @Override
        public CmHandleState nextState() {
            return this;
        }

        @Override
        public String cmHandleState() {
            return "LOCKED";
        }
    };

    public abstract CmHandleState nextState();
    public abstract String cmHandleState();


The state machine transitions are implemented using the enum's abstract nextState() method.

PreviousState() can also be implemented, so if the state needs to go from 'READY' to 'LOCKED' for example, this can also be done without having to be explicitly stated.

Advantages of Enum Stating Machine

  • Easy to Implement
  • Can provide the logic for the transition implementation without having to explicitly state it.
  • Cleaner and Easier to read which states can be transitioned to other states.