Click here to Skip to main content
15,887,135 members
Articles / Web Development / ASP.NET
Tip/Trick

Illustrating the State Pattern with a Very Basic Example

Rate me:
Please Sign up or sign in to vote.
4.79/5 (8 votes)
29 Dec 2015CPOL2 min read 26.7K   166   12   7
A simplified example is used to describe the state pattern

Introduction

The state pattern is a very much used design pattern and it allows a context to change its behavior as the state of the context changes.

Problem

For example, we have a real time scenario. In a traffic signal, the state of the signal changes all the time. The red signal which indicates to stop, the green which indicates to go and so on. In this situation, the state of the signal changes from one state to another. If we implement this scenario in the traditional approach, then it is very clumsy and a maintenance nightmare. We can resolve these kind of problems using state pattern.

Using the Code

In the discussed problem, there are two functionalities; one is change the state and one is report the state. So an interface is required to declare these three methods. Let's take ITrafficLight as interface here.

Change State: Which means the signal changes from one state to another.

Report State: What is the signal state after changes its state means ("Red", "Yellow" or "Green").

C#
public interface ITrafficLight
{
    void change(TrafficLight light);
    void ReportState();
}

A class TrafficLight is required to hold the interface property and set the current state and display the changed state.

C#
public class TrafficLight
{
    public ITrafficLight state { get; set; }
    public void change()
    {
        state.change(this);
    }
    public void Reportstate()
    {
        state.ReportState();
    }
}

Three classes are required to implement the interface methods:

  • GreenLight
  • RedLight
  • YelloLight

All these three classes implement the ITrafficLight interface which means the classes need to specify the changeState and the ReportState. The interesting thing here is we will always pass the next state to the current class. For suppose after the green light indication, the yellow light follows and the red light follows after yellow. So why we are passing the "YelloLight" instance in GreenLight class and so on.

C#
light.state = new YelloLight(); //For the GreenLight class
 public class GreenLight:ITrafficLight
    {
        public void change(TrafficLight light)
        {
            light.state = new YelloLight();
        }

        public void ReportState()
        {
            Console.WriteLine("Green light");
        }
    }

public class RedLight:ITrafficLight
    {
        public void change(TrafficLight light)
        {
            light.state = new GreenLight();
        }

        public void ReportState()
        {
            Console.WriteLine("Red Light");
        }
    }

 public class YelloLight:ITrafficLight
    {
        public void change(TrafficLight light)
        {
            light.state = new RedLight();
        }

        public void ReportState()
        {
            Console.WriteLine("Yellow Light");
        }
    }

Finally, take an object for the TrafficLight class and inform the state and keep on changing the state. So it will automatically follow the state and changes its state.

C#
TrafficLight light = new TrafficLight();
            light.state = new RedLight();
            while(true)
            {
                light.change();
                light.Reportstate();
            }
            Console.ReadKey();

The output is as expected:

RedLight

GreenLight

YellowLight

.

Points of Interest

Using the state pattern is much easier to resolve and implement the problems which always changes their states.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader
United States United States
Experienced Lead developer having 17+ years with a passion for developing innovative programs that expedite the efficiency and effectiveness of organizational success. Well-versed in technology and writing code to create systems that are reliable and user-friendly. A skilled leader who has the proven ability to motivate, educate, and manage a team of professionals to build software programs and effectively track changes. Confident communicator, strategic thinker, and innovative creator to develop software that is customized to meet a company’s organizational needs and further its success.

Comments and Discussions

 
QuestionCoupled too Tightly Pin
James Lonero4-Jan-16 6:08
James Lonero4-Jan-16 6:08 
GeneralMy vote of 5 Pin
Member 43208442-Jan-16 22:59
Member 43208442-Jan-16 22:59 
QuestionIs this implementation correct? Pin
George Swan30-Dec-15 11:50
mveGeorge Swan30-Dec-15 11:50 

Rajesh. Thanks for the interesting article. I am not sure that your implementation of the State Pattern is entirely correct. You have State objects but you do not have a Context object that can change state. My understanding is that the State objects are supposed to encapsulate the behaviour of a specific state of the Context object. You are simply changing one State object for another State object. It seems to me that your State objects are not encapsulating the state of a traffic light, they are each a traffic light and you have three of them.

Could I suggest the following implementation template? Say you have a Traffic Flow Controller and the controller can have three states
Stop State:
Controller Displays Red Light,
Controller Displays ‘Stop’ message,
Controller’s interval is set to 3 minutes
Caution State:
Controller Displays Amber Light,
Controller Displays ‘Proceed with caution’ message,
Controller’s interval is set to 1 minute
Go State:
Controller Displays Green Light,
Controller Displays ‘Go!’ message,
Controller’s interval is set to 4 minutes

You would have 3 State objects of Type ITrafficFlowControllerState
StopState, CautionState and GoState.
Each State object will be responsible for setting the controller‘s corresponding state. When the controller’s interval timer times out, the current State object’s ChangeState method is called which changes the state to that of its successor (stored in the object’s Successor property) and away you go again. Best wishes, George.


GeneralNice and easy to understand Pin
Salam Y. ELIAS20-Jan-15 0:53
professionalSalam Y. ELIAS20-Jan-15 0:53 
Questionhave look at http://smc.sourceforge.net/ Pin
marc borgers31-Dec-14 0:24
marc borgers31-Dec-14 0:24 
GeneralMy vote of 5 Pin
N Srinivas 201329-Dec-14 2:51
N Srinivas 201329-Dec-14 2:51 
QuestionGreat Article Pin
Dimple Kumar Sharma26-Dec-14 4:05
Dimple Kumar Sharma26-Dec-14 4:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.