Last active
February 27, 2016 19:24
-
-
Save kostrse/b8913471ee6e64488bb1 to your computer and use it in GitHub Desktop.
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
public class StateSwitch | |
{ | |
private readonly Action enterAction; | |
private readonly Action leaveAction; | |
private readonly bool leaveOnSuspend; | |
private uint counter; | |
private bool entered; | |
private bool suspended; | |
public StateSwitch(Action enterAction, Action leaveAction, bool leaveOnSuspend = false) | |
{ | |
this.enterAction = enterAction; | |
this.leaveAction = leaveAction; | |
this.leaveOnSuspend = leaveOnSuspend; | |
} | |
public void Enter() | |
{ | |
if (this.counter++ == 0 && !this.suspended) | |
{ | |
this.DoEnter(); | |
} | |
} | |
public void Leave() | |
{ | |
if (this.counter == 0) | |
{ | |
throw new InvalidOperationException("Unable to leave state more times than it was entered."); | |
} | |
if (--this.counter == 0 && !this.suspended) | |
{ | |
this.DoLeave(); | |
} | |
} | |
public void Suspend() | |
{ | |
if (this.suspended) | |
{ | |
return; | |
} | |
if (this.leaveOnSuspend && this.entered) | |
{ | |
this.DoLeave(); | |
} | |
this.suspended = true; | |
} | |
public void Resume() | |
{ | |
if (!this.suspended) | |
{ | |
return; | |
} | |
this.suspended = false; | |
if (this.counter == 0 && this.entered) | |
{ | |
this.DoLeave(); | |
} | |
else if (this.counter > 0 && !this.entered) | |
{ | |
this.DoEnter(); | |
} | |
} | |
private void DoEnter() | |
{ | |
this.entered = true; | |
this.enterAction(); | |
} | |
private void DoLeave() | |
{ | |
this.entered = false; | |
this.leaveAction(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment