Chris's coding blog

C# Design Patterns: the State pattern

March 09, 2009

Summary

Like a finite state machine but implemented using a class for each state, rather than an enumeration and/or switch statement.

Example

A basic example would be a traffic light system - GreenState, AmberState, RedState. Each of the classes is expected to implement an IState() interface or subclass a base class which contains the states that can be moved from/to via methods. The pattern lends itself to allowing each class to handle the state it represents in more detail (and a lot easier to read and maintain) than a giant switch statement. The current state (called the Context) is passed to each class in each method.

For games where your current state (context) is important, like (MMO)RPG games, the State pattern could be used. For example some games of this genre require you to have perform one action, say cast a specific spell, before you can perform another spell.

namespace DesignPatterns
{
/// <summary>
/// Default State that every state inherits from.
/// </summary>
public abstract class State
{
/// <summary>
/// Holds the current state we're in.
/// </summary>
public State CurrentState
{
get;
set;
}
public virtual string SitDown(State context)
{
return "";
}
public virtual string Walk(State context)
{
return "";
}
public virtual string Run(State context)
{
return "";
}
}
public class SittingState : State
{
public override string SitDown(State context)
{
context.CurrentState = new SittingState();
return "Sitting down.";
}
public override string Walk(State context)
{
context.CurrentState = new WalkingState();
return "I'm walking.";
}
public override string Run(State context)
{
return "I can't run while I'm sitting down.";
}
}
// (WalkingState and RunningState classes have been cut out, see the download)
}
view raw gistfile1.cs hosted with ❤ by GitHub

csharpdesign-patterns

I'm Chris Small, a software engineer working in London. This is my tech blog. Find out more about me via GithubStackoverflowResume