dimanche 10 mai 2020

Transition state VS switch case what is the best way to apply state machine [C#]

I am C# developer many time i use state machine with my work.There are many ways that I've done it before the first one is transition state ( I dont know what is actually call the name for this way)

Example transition state:

public int wait_input_from_something;

public void state_a()
{
     while(true)
  {

     if(wait_input_from_something == 1)
         state_b();    // Actually it not call next state easy like this but the concept is the same.
      else if (wait_input_from_something == 2)  
         state_c();
   }

}

public void state_b()
{
     while(true)
  {
     if(wait_input_from_something == 3)
        state_a();
     else if (wait_input_from_something == 4)
        state_d();
  }
}


This is only show the concept that directly transition from one state to the others this apply while loop inner each method if nessessary.

The second thing is Switch-Case

while(true)
{
   switch (wait_input_from_something)
         {
             case 1:
                    state_b();
                    break;
              case 2:
                    state_c;
                    break;
              case 3:
                    state_a();
                    break;
              case 4:
                    state_d;
                    break;

            }
}


All Above Example not contains Logic code but you can get the idea of how to transition from one state to the others. Actually i prefer the first one transition state because the code can easily to monitor what going on for each states we can diagnosed one by one for each state.

Can you advice what is the best way for applied complicated application using state machine ? advantage/disadantage of each solution?

Aucun commentaire:

Enregistrer un commentaire