domenica 28 aprile 2019

Design Patterns : State Pattern

State pattern defines a way to manage a state machine, if you don't use design patterns, in traditional programming, you will use a switch statement to move throw the states.
You have to create an interface with a method for the action to do in a specific state, then you have to create concreate classes for each state and implement the method to implement the state, then you need a context to switch the states. The client will use the context to change the states.

public interface IStatus
{
     void ApplyStatus();
}

public class StateInit : Status
{
     void ApplyStatus()
     {
           InitializeMachine();
     }
}

public class StateRunning : Status
{
     public void ApplyStatus()
     {
           RunMachine();
     }
}

public class StateStop : Status
{
     public void ApplyStatus()
     {
           StopMachine();
     }
}

public class Context
{
      private Status state,

      public void SetStatus(Status status)
      {
            state = status;
      }

      public ChangeStatus()
     {
           state.ApplyStatus();
     }
}

Usage:
Contex contex;
context.SetStatus(new StateInit());
context.ChangeStatus();
context.SetStatus(new StateRunning());
context.ChangeStatus();
context.SetStatus(new StateStop());
context.ChangeStatus();

Nessun commento:

Posta un commento