How to create a simple state machine in java

前端 未结 1 1697
感情败类
感情败类 2021-02-02 16:00

I am currently learning java and would like to know how to control state in a OO way. I implemented a Pong app. If I wanted multiple states like gameplay and menu, and each one

1条回答
  •  时光说笑
    2021-02-02 16:34

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

    public enum State {
    
        ONE {
            @Override
            public Set possibleFollowUps() {
                return EnumSet.of(TWO, THREE);
            }
        },
    
        TWO {
            @Override
            public Set possibleFollowUps() {
                return EnumSet.of(THREE);
            }
        },
    
        THREE // final state 
    
        ;
        public Set 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.

    0 讨论(0)
提交回复
热议问题