SgDotNet
Singapore Professional .NET User Group -For Cool Developers

State pattern

Latest post 09-14-2006 11:50 AM by pvijayaramaraju. 4 replies.
  • 08-02-2005 10:09 PM

    State pattern

    State pattern dynamically changes the state class and its behabior when its internal state changes.   

    What is the practical usage of this pattern? I have no idea where in NET framework this pattern is applied. I do know that it is very useful and practical to apply this pattern when one needs to dynamically change class represented by a state      

    Let's look at the coding structure of this pattern:

    using System;

    abstract class State
    {
      abstract public void ChangeState(Context context);
      abstract public string Message();
    }

    class SleepyState : State
    {
      override public void ChangeState(Context context)
      {
        context.State = new WakeupState();   
      }
     
      override public string Message()
      {
        return "I'm sleeping";
      }
    }

    class WakeupState : State
    {
      override public void ChangeState(Context context)
      {
        context.State = new EnergizedState();   
      }
     
      override public string Message()
      {
        return "I'm waking up";
      }
    }

    class EnergizedState : State
    {
      override public void ChangeState(Context context)
      {
        context.State = new SleepyState();   
      }
     
      override public string Message()
      {
        return "I'm energized";
      }
    }

    class Context
    {
      public Context(State state)
      {
        this.state = state;
      }

      private State state;
      public State State
      {
        get{ return state; }
        set{ state = value; }
      }

      public void Request()
      {
        state.ChangeState( this );
      }

      public void Show()
      {
        Console.WriteLine( "State: " + state.Message() );
      }
    }

    public class Client
    {
      public static void Main( string[] args )
      {
        // Start with SleepyState
        Context c = new Context(new SleepyState() );
        c.Show();

        // Change to WakeupState
        c.Request();
        c.Show();

        // Change to EnergizedState
        c.Request();
        c.Show();
       
        // Go back to SleepyState
        c.Request();
        c.Show();
      }
    }

    Here is a summary of the structural concept of the State pattern:
    1. Create an abstract base class and its common interface
    2. Create concrete sub classes overriding the require methods, especially the method to actually change the state and class  
    3. Create a stand alone class (Context or any name you prefer) to hold the current state and also provides logic to change to a different state 
    4. Client can now instantiate the context object, request a change from one state to another     

    Anyone has any idea to use it differently or has a different view about this pattern, love to hear from you.

    Hope it helps

  • 02-03-2006 5:22 PM In reply to

    Re: State pattern

    This calls for a very rigid hard-coded flow. Wouldn't a State Machine or Work Flow engine provide more usefulness than this? (supposing one wants to mix and match sequences dynamically)

    Also, does an object not best assess what state it should be in by its own actions (methods) and data changes (properties)?

    The melody of logic will always play out the truth. ~ Narumi Ayumu, Spiral

  • 02-03-2006 11:39 PM In reply to

    Re: State pattern

     icelava wrote:
    This calls for a very rigid hard-coded flow. Wouldn't a State Machine or Work Flow engine provide more usefulness than this? (supposing one wants to mix and match sequences dynamically)

    Yes. In fact in the upcoming Windows Workflow Foundation, the State Machine workflow can be used to do this.

  • 02-03-2006 11:55 PM In reply to

    Re: State pattern

     icelava wrote:

      This calls for a very rigid hard-coded flow.

    Not really.. In the State pattern, the respective State objects are responsible for the change to other states. instead of delegating this responsibiliy to the object itself. The key idea is that the state knows best.. (i.e. If this action is performed, it knows it should transition to antoher state or remain in its current state).  This allows a developer to introduce new states without changing the main object code.  Also,  the overall problem space of state transition is simplified (or reduced). Instead of a global view of what causes what to change to which state, we just need to focus on how a state would change locally.

     icelava wrote:

    Also, does an object not best assess what state it should be in by its own actions (methods) and data changes (properties)?

    If you let the object best assess what state it should be in by its own action, then the state transition is most likely captured in a SWITCH/CASE block in each method that needs to determine state transition, which makes it less flexible.

    In certain context (when the no of states is relatively small), there are merits to using State pattern.  However, there are always arguments against the use of State patterns in situations when you need to model a large number of states.

    Check out


    for several interesting discussions on the use of State patterns.

  • 09-14-2006 11:50 AM In reply to

    Re: State pattern

    Hi,
    I dont know if this post is out dated but am posting my views never the less.

    "Anyone has any idea to use it differently".

    The common misconception I see lot of times in local Disgn pattern groups is that Design patterns are to be "used" rather than be "followed".

    You never use design patterns to design an application. instead you design an application and check if any parts of your application follows any design pattern. and then document it. Design patterns allow you to conceptualise your design at a much higher.

    If you have ever designed an application. There is a very high chance that you have already used design patterns. even if you are ignorant of what a design pattern is.

    Design patterns help Non designers appreciate, understand and also help them catch up with the designing art. so it actually speeds up your Learning curve.

    Coming to the above post.
    Truth  is I have fully not understood the question. I actually can see the question in  2 ways and dont know what the actual intent might have been.

    1) Can a state pattern be imlemented in any other way.
    2) Can the design given above be used in other scenarios and not call it the state pattern.


    Answer to question 1 :  Yes why not.
    The design shown above does not take into consideration many issues that commonly occur in Real Time like
     1) You may want to make a state transition only response to an event respond to events
     2) Transition to multiple states might be possible.

    state Pattern as i know only mentions to abstract the behaviour of the state ( please dont take my word for that and refer a book. it is been a very long time since i read it) So any design which abstracts that behaviour can be said to follow the state design pattern. There is a hell lot of literature on state charts and thier implementation. you can find a variety of designs and implementations if you search.


    Answer to question 2 : This is a very interesting design and can be used in a hell lot of places some of them could be

     1) An Alternative to Inheritance
     2) a modification of this can be used in scenarios wherein you need to change the       behaviour of an Object at runtime
     3) a place where you want your design to follow the strategy pattern.
     etc... etc...

     

     

Page 1 of 1 (5 items) | RSS
Copyright SgDotNet 2004-2008
Powered by Community Server (Commercial Edition), by Telligent Systems