Created
February 9, 2013 19:26
-
-
Save yetanotherchris/4746689 to your computer and use it in GitHub Desktop.
State design pattern example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment