State Design Pattern

 definition
 UML diagram
 participants
 sample code in C#



definition

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

Frequency of use:   medium

UML class diagram


participants

    The classes and/or objects participating in this pattern are:

  • Context  (Account)
    • defines the interface of interest to clients
    • maintains an instance of a ConcreteState subclass that defines the current state.
  • State  (State)
    • defines an interface for encapsulating the behavior associated with a particular state of the Context.
  • Concrete State  (RedState, SilverState, GoldState)
    • each subclass implements a behavior associated with a state of Context

sample code in C#

This structural code demonstrates the State pattern which allows an object to behave differently depending on its internal state. The difference in behavior is delegated to objects that represent this state.

Show code

// State pattern -- Structural example




This real-world code demonstrates the State pattern which allows an Account to behave differently depending on its balance. The difference in behavior is delegated to State objects called RedState, SilverState and GoldState. These states represent overdrawn accounts, starter accounts, and accounts in good standing.

Show code

// State pattern -- Real World example




This .NET optimized code demonstrates the same real-world situation as above but uses modern, built-in .NET features, such as, generics, reflection, object initializers, automatic properties, etc.

Show code

// State pattern -- .NET optimized




   Better Code 
   Better Career 
   Better Lifestyle 


.NET
Design Pattern
Framework 4.5


 
C# and VB.NET


   Includes:

  Gang of Four Patterns
  Head First Patterns
  Enterprise Patterns
  Multi-Tier Patterns

  Repository Pattern
  Unit-of-Work Pattern
  CQRS Pattern
  Active Record Pattern

  Model View Controller
  Model View Presenter
  Model View ViewModel

  SparkTM RAD Platform
  Art Shop MVC Application
  Much more...

Click here for details

-- Instant Access --
Instant Download