Introduction
The State Pattern (also referred to as State Design Pattern) is one of the behavioral patterns. It defines a manner for controlling communication among classes or entities. It is used to change the behavior of the object when the object's internal state is changed. This pattern helps objects to change it state without changing the interface (used to access the object) or lose the current state. This change of the state of the class or object is hidden from the outer world with the use of a context (also known as wrapper object). The State Pattern can be used to implement complex decision-making algorithms represented as a flow chart or state diagram. A State Pattern can also be implement where various states exist and each state has a specific action.
Structure
The UML Class Diagram of the State Pattern is as below. 
This pattern has three main parts, context, statebase and concrete state (State A, State B, State C and so on). The Context is also called Client. Client does not access any state directly. It only holds a concrete state object that provides the current behavior of the context object. StateBase is the base class of all concrete states. It may be an abstract class or an interface. Concrete class (State A, State B and State C) is provided functionality that will be used for change and hold the behavior of the context object.
The basic code structure of the State Design Pattern implementation uses C# as in the following. Here starting state of context is passed through a constructor. A "Request" method of Context is used to change the current state to the next state. Internally it calls the StateBase.Chage() method. The StateBase.Chage() method switches the state of the passed context object to the next state. In this example the state change sequence is as below.
State Code
public interface StateBase
{
void Change(Context context);
}
public class StateA : StateBase
{
public void Change(Context context)
{
//Change state of context from A to B.
context.State = new StateB();
Console.WriteLine("Change state from A to B.");
}
}
public class StateB : StateBase
{
public void Change(Context context)
{
//Change state of context from B to C.
context.State = new StateC();
Console.WriteLine("Change state from B to C.");
}
}
public class StateC : StateBase


Join the conversation! Your thoughts help the community grow.