Design Patterns : State Pattern

State Pattern is share a lot of similarities with Strategy Pattern, but has its own fundamental differences as well. The State pattern allows to change the behavior of a method, depending on the state of an object, in other words it encapsulates the behavior dependent on the state (the What). This is different from the Strategy Pattern which encapsulates the algorithm (the How).

As always, let’s begin by writing a code that showcases the issues faced when we are not using State Pattern.
public enum eState
{
  CardNotInserted,
  NotValidated,
  Validated
}
public class ATMWithoutState
{
  public eState CurrentState { get; set; }


  public void DoOperation()
  {
    switch (CurrentState)
    {
     case eState.CardNotInserted:
        Console.WriteLine("Current: Card Not Inserted, Next: Insert Your Card");
        break;
     case eState.NotValidated:
        Console.WriteLine("Current: Not Valided, Next: Validate your card by entering PIN");
        break;
case eState.Validated:
       Console.WriteLine("Current: Validated, Next: Please enter amount to withdraw");
       break;
    }
  }
}

The switch case exposes the most obvious flaw of this approach, we need to alter the class to add a new state, which is a clear violation of the Open Closed Principle. This is where the State Pattern comes into play, which gives a separate behavior for DoOperation method for different states of Object.

public interface IAtmState
{
  void DoOperation();
}

public class ATMWithState
{
  public IAtmState CurrentState { get; set; }

  public void DoOperation()
  {
    CurrentState.DoOperation();
  }
}

public class CardNotInsertedState : IAtmState
{
  public void DoOperation()
  {
    Console.WriteLine("Current: Card Not Inserted, Next: Insert Your Card");
  }
}

public class NotValidatedState : IAtmState
{
  public void DoOperation()
  {
    Console.WriteLine("Current: Not Valided, Next: Validate your card by entering PIN");
  }
}

public class ValidatedState : IAtmState
{
  public void DoOperation()
  {
    Console.WriteLine("Current: Validated, Next: Please enter amount to withdraw");
  }
}

The complete code described in this post in available in my GitHub.

One thought on “Design Patterns : State Pattern

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s