State Pattern

In this article I am going to explain the State Pattern. It is one among the 23 design patters and provides a good solution to a common problem.
 
As usual the pattern starts with a challenge and then implementing the solution using the pattern.

Challenge

You are working on a job processing application. The application can handle only 1 job at a time. So when a new job arrives the system response will be weird. How to provide a better approach to the above problem?

Definition

Allow an object to alter its behavior when its internal state changes. The object will appear to change its class."

Implementation

An enumeration named JobState is used to define the states used in our application.

    public enum JobState
    {
        Ready,
        Busy
    }

This enumeration is used inside our Job class.

    public class Job
    {
        private JobState _State;

        public JobState State
        {
            get { return _State; }
            set
            {
                _State = value;

                if (OnJobStateChanged != null)
                    OnJobStateChanged(this, _State);
            }
        }

        public bool AddJob(object jobParameter)
        {
            switch (State)
            {
                case JobState.Ready:
                    {
                        DoJob();
                        return true;
                    }
                case JobState.Busy:
                    {
                        return false;
                    }
            }

            return false;
        }
    }


In the AddJob() method we can see the new job is taken only if the JobState is in Ready state. Here true will be returned by the method. If there is another job running, then the new job will not be queued and false will be returned.

Thus the object Job changes the behavior based on the internal state.

Application

The associated application contains the classes we discussed.

On executing the windows application and clicking the Assign Job button, you can see the following screen:

StatePattern.jpg

While a job is in process, we cannot add another job. If a try is made the response is:

Summary

In this article we have seen about State Pattern. The attachment file contains the source code of the application we have discuseed.
 

Up Next
    Ebook Download
    View all
    Learn
    View all