How to create a simple state machine in java

ε祈祈猫儿з 提交于 2019-12-02 20:45:08
Sean Patrick Floyd

You can simulate a basic FSM (Finite State Machine) using enums:

public enum State {

    ONE {
        @Override
        public Set<State> possibleFollowUps() {
            return EnumSet.of(TWO, THREE);
        }
    },

    TWO {
        @Override
        public Set<State> possibleFollowUps() {
            return EnumSet.of(THREE);
        }
    },

    THREE // final state 

    ;
    public Set<State> possibleFollowUps() {
        return EnumSet.noneOf(State.class);
    }

}

While the code to generate this will be very verbose if things get more complicated, the nice part is that you get compile-time safety, thread-safety and high performance.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!