Author - Neeraj Sharma Post Views - 39 views
State Design

State Design Pattern

Allow objects to adjust their behavior in response to changes in their internal states using State Design Pattern. Depending on object state, a class modifies its behavior. As part of the State Pattern, we design objects to represent distinct states as well as a context object whose behavior changes as its state object does.

There are three major components to this pattern: context, statebase, and concrete state. The client is another name for the Context. The client does not directly access any state. It merely keeps a concrete state object that describes the context object’s present behavior. All concrete states have StateBase as their base class. It might be an interface or an abstract class. Functionality that will be utilized to alter and hold the behavior of the context object is supplied for the concrete classes.

This pattern has three main parts

  1. Context
  2. State
  3. ConcreteState

State Design Pattern

Context:
This class contains a concrete state object that behaves in accordance with its current state.

State:
The Context object uses this interface to access the functionality that is changeable.

ConcreteStateA/B:
These classes implement the State interface and give the Context object the actual functionality it needs. For each state of the Context object, a concrete state class offers functionality that is specific to that state.

Implementation Code:

public interface BaseStateClass
{
void Change(Context context);
}
public class State1: BaseStateClass
{
public void Change(Context context)
{
context.State = new State2();
Console.WriteLine("Change state from 1 to 2.");
}
}
public class State2 : BaseStateClass
{
public void Change(Context context)
{
context.State = new State3();
Console.WriteLine("Change state from 2 to 3.");
}
}
public class State3 : BaseStateClass
{
public void Change(Context context)
{
context.State = new State1();
Console.WriteLine("Change state from 3 to 1.");
}
}
public class Context
{
public Context(BaseStateClass state)
{
State = state;
Console.WriteLine("Create an object of context class with initial State.");
}
public BaseStateClass State { get; set; }
public void Request()
{
State.Change(this);
}
}
static void Main(string[] args)
{
Context context = new Context(new State1());
//Change state request from 1 to 2.
context.Request();
//Change state request from 2 to 3.
context.Request();
//Change state request from 3 to 1.
context.Request();
}

People having good command over the French language can get a French certification from StudySection. StudySection offers both beginner level and expert level French Certification Exams to test the ability to communicate in the French language.

Leave a Reply

Your email address will not be published. Required fields are marked *

fiteesports.com rivierarw.com cratosroyalbet betwoon grandpashabet grandpashabet giriş deneme bonusu veren siteler casino siteleri