Explanation of State Design Pattern

Explanation of State Design Pattern

Hello everyone, in this article we are going to talk about State Design Pattern within Behavioral Design patterns. We are going to make a simple description and an example with C# programming language.

Let's get started.

Sometimes, a specification of our project may have different operation modes. This states maybe two or more. Normally we we use the if-else/if to decide which mode is active. In state design pattern we set the modes automatically when the status changed. We can add so many states easly instead of change the whole project core source.
For example, if we try to power on our mobile phone, it must be powered off. We can not power on when it is powered on. With state design pattern we set the device state as powered off or powered on
Before example you should have an idea of the below terms:
  • Context: This is the object or component which we are going to change its states.
  • State: This interface class that contains all concreteStates specifications and what they do.
  • ConcreteState: These classes provide the states to the context from state interface.

Now let's start build our example.
In our example we are going to make an aircrafts air ground modes. When we set the aircraft air mode it will act like in air, and when we set it as Ground Mode it will act like at Ground.

Below image you can see the schematic of my example. State Design Pattern Schematic
This interface will derive the concrete state classes. All concrete states will have a change function you can add here what function do you need in your project like save it to a global variable or remote server.
AirGroundState.cs

namespace StatePattern_Example
{
    //This interface will derive the concrete state classes
    //All concrete states will have a change function
    //you can add here what function do you need in your project
    //like save it to a global variable or remote server.
    interface AirGroundState
    {
        void ChangeState(Aircraft _aircraft);
    }
}
This concrete state class was derived from State interface. This state classes will operate the state changings. Here we can make the required tasks before and after state changings.
This class will change the state to the air state.
GroundState.cs

using System;

namespace StatePattern_Example
{
    //this concrete state class was derived from State interface.
    //This state classes will operate the state changings.
    //Here we can make the required tasks before and after state changings.

    //This class will change the state to the air state.
    class GroundState : AirGroundState
    {
        public void ChangeState(Aircraft _aircraft)
        {
            _aircraft.airGndState = new AirState();
            Console.WriteLine("Air/Ground Mode switched to Air Mode...");
        }
    }
}
AirState .cs

using System;

namespace StatePattern_Example
{
    //This class will change the state to the Ground state.
    class AirState : AirGroundState
    {
        public void ChangeState(Aircraft _aircraft)
        {
            _aircraft.airGndState = new GroundState();
            Console.WriteLine("Air/Ground Mode switched to GND Mode...");
        }
    }
}
This class is our context class. States are belong to this context class and we are going to manage those state class from here. We have to store the current state in the context class Also we need to start the context with initial state. I use contructor class to specify the initial state Then we are going to change the current state with switch method.
Aircraft.cs

using System;

namespace StatePattern_Example
{
    //This class is our context class. 
    //States are belong to this context class and 
    //we are going to manage those state class from here.
    class Aircraft
    {
        //We have to store the current state in the context class
        public AirGroundState airGndState;

        //Also we need to start the context with initial state.
        //I use contructor class to specify the initial state
        public Aircraft(AirGroundState _initialState)
        {
            this.airGndState = _initialState;
        }

        //Then we are going to change the current state with switch method.
        public void switchAirGNDState()
        {
            airGndState.ChangeState(this);
            Console.WriteLine("---------------------------------------");
        }
    }
}
At the main program we need to initialize the context class with initial state and we can make state changings with method which belongs to context class.
Program.cs

using System;

namespace StatePattern_Example
{
    class Program
    {
        //at the main program we need to initialize the context class with initial state.
        //and we can make state changings with method which belongs to context class.
        static void Main(string[] args)
        {
            Console.Title = "State Design Pattern Example - Thecodeprogram";

            Aircraft aircraft = new Aircraft(new GroundState());
            aircraft.switchAirGNDState();
            aircraft.switchAirGNDState();
            aircraft.switchAirGNDState();
            aircraft.switchAirGNDState();
            aircraft.switchAirGNDState();

            Console.ReadLine();
        }
    }
}
Below image you can see the output of the example application. State Design Pattern Example Output

That is all in this article.

You can reach the example code on Github : https://github.com/thecodeprogram/StatePattern_Example

Have a good State managing of the contexes.

I wish you have healthy days.

Burak Hamdi TUFAN.


Tags


Share this Post

Send with Whatsapp

Post a Comment

Success! Your comment sent to post. It will be showed after confirmation.
Error! There was an error sending your comment. Check your inputs!

Comments

  • There is no comment. Be the owner of first comment...