A sImple state machine for a cycle, with an observer
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
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