Skip to content

Instantly share code, notes, and snippets.

@eastmad
Last active August 31, 2022 18:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eastmad/c8672e390a01af51fd03efbd1d8849cb to your computer and use it in GitHub Desktop.
Save eastmad/c8672e390a01af51fd03efbd1d8849cb to your computer and use it in GitHub Desktop.
A sImple state machine for a cycle, with an observer
using System.Diagnostics;
using System.Threading;
using System.Timers;
using TheNewStack;
namespace TheNewStack
{
public enum SeasonalState { Spring, Summer, Autumn, Winter }
public class SimpleStateMachineWithObserver
{
public Season CurrentSeason;
public SimpleStateMachineWithObserver()
{
Farmer farmer = new Farmer();
Season season = CurrentSeason = new Season(SeasonalState.Spring, farmer.SpringWelcome);
season = season.NextSeason = new Season(SeasonalState.Summer, farmer.SummerWelcome);
season = season.NextSeason = new Season(SeasonalState.Autumn, farmer.AutumnWelcome);
season = season.NextSeason = new Season(SeasonalState.Winter, farmer.WinterWelcome);
season.NextSeason = CurrentSeason;
}
public Season Next()
{
return CurrentSeason = CurrentSeason.NextSeason;
}
public class Season
{
readonly SeasonalState seasonstate;
public Season NextSeason;
private Action action;
public Season(SeasonalState seasonstate, Action action)
{
this.seasonstate = seasonstate;
this.action = action;
}
public void Welcome()
{
action();
}
}
}
public class Farmer
{
public void SpringWelcome() => Console.WriteLine("Spring is here. Spread the fertiliser!");
public void SummerWelcome() => Console.WriteLine("Summer is here. Cut the hay!");
public void AutumnWelcome() => Console.WriteLine("Autumn is here. Harvest time!");
public void WinterWelcome() => Console.WriteLine("Winter is here. Feed the cows!");
}
}
public class Program
{
static void Main(String[] args)
{
SimpleStateMachineWithObserver s = new SimpleStateMachineWithObserver();
for (int i = 0; i < 6; i++)
{
s.CurrentSeason.Welcome();
s.Next();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment