Skip to content

Instantly share code, notes, and snippets.

@gregmajor
Created August 25, 2012 19:58
Show Gist options
  • Save gregmajor/3470274 to your computer and use it in GitHub Desktop.
Save gregmajor/3470274 to your computer and use it in GitHub Desktop.
State Pattern Example
/*
* THE STATE PATTERN
* - Allows an object to alter its behavior when its internal state changes
* - The object "transforms" and appears to be completely different
*/
using System;
class Program
{
static void Main(string[] args)
{
var mp3Player = new MP3PlayerContext();
mp3Player.Play();
Console.WriteLine(string.Format("The MP3 player state is {0}.", mp3Player.CurrentState));
mp3Player.Play();
Console.WriteLine(string.Format("The MP3 player state is {0}.", mp3Player.CurrentState));
}
}
public class MP3PlayerContext
{
public MP3PlayerContext()
{
this.CurrentState = new StandbyState();
}
public MP3PlayerContext(IState state)
{
this.CurrentState = state;
}
public IState CurrentState { get; set; }
public void Play()
{
this.CurrentState.PressPlay(this);
}
}
public interface IState
{
void PressPlay(MP3PlayerContext context);
}
public class StandbyState : IState
{
public void PressPlay(MP3PlayerContext context)
{
context.CurrentState = new PlayingState();
}
}
public class PlayingState : IState
{
public void PressPlay(MP3PlayerContext context)
{
context.CurrentState = new StandbyState();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment