Design Pattern problem involving N states and transitions between them

后端 未结 6 1389
春和景丽
春和景丽 2020-12-12 16:44

I have a problem at hand and I am not getting which design pattern to use. The problem goes as such:

I have to build a system which has \'N\' states and my system ha

6条回答
  •  一整个雨季
    2020-12-12 17:28

    This sounds like the typical use for a finite state machine

    in short, the state machine describes the various states in which your system can be, and under which conditions it can go from state to state. A state machine is described exactly as your English description. And it can be formally described using state diagrams

    in code you could make a state machine like this:

     enum State { Init, ShowMenu, ShowMsg, DisplayVideo, Exit };
     State state = State.Init;
    
     while (state != State.Exit)
     {
          switch(state)
          {
               case State.Init:
                    init();
                    state = State.ShowMenu;
                    break;
               case State.ShowMenu:
                    if(lastMenuItemSelected==1) state = State.ShowMsg;
                    if(lastMenuItemSelected==2) state = State.DisplayVideo;
                    break;
               case State.ShowMsg:
                    ....
                    break;
               ....
     }
    

    I'm not sure if I got the exact syntax correct for Java...I'm more into C#

提交回复
热议问题