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




Need to know more?

    see what others are saying about the State pattern



  • Better Code
  • Better Career
  • Better Lifestyle


Design Pattern
FrameworkTM 4.0


 
C# and VB.NET


     Here's what you get:
  • Gang of Four Patterns
  • Head First Patterns
  • Enterprise Patterns
  • SOA Patterns

  • WPF Best Practices
  • WCF Best Practices
  • LINQ Best Practices

  • Model View Controller
  • Model View Presenter
  • Model View ViewModel

  • More...

Click here for details

-- Instant Access --
Instant Download