jeudi 27 mai 2021

Best way to construct complex states with state pattern?

I have a menu that can be in different states so I decided to use the state pattern. Reading online about the pattern seems like the usual way is to construct states from another state but this will not work for me because I have more complex states which need other dependencies. I could pre-create all states in a context object and then switch states from the context object, but I also need some info from the previous state so it becomes messy too.

     class State1 {
         public State1(Context context, /*some complex constructor*/) {
         }
         public void Action() {
            //Something happend and we want to transition to other state
               
            //Usual way 
            //this will not work because state1 doesnt have 
            //dependencies to construct state2
            //context->SetState(new State2());
            

            //My current way
            //This is better because it works, but you will have to create
            //such functions for every state and context object needs to be 
            //modified if new states are added which is not ideal
            context->SetState2(/*something produced by action in state1*/);
         }
     }   

    class State2 {
         public State2(Context context, /*some complex constructor*/) {
         }
     }   
     
     
    class Context {
      //has current state 
    }

Is this a sign of a bad design?
Is there a clean solution to this or I thinking too much about this?

Aucun commentaire:

Enregistrer un commentaire