Click here to Skip to main content
15,867,771 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.5K   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 
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.