Strictly speaking, if you implement the classic GoF state template, then state subclasses themselves are responsible for knowing and performing state transitions. The state owner is not responsible for transition management, and a significant part of the intent of the template is to encapsulate state transition behavior in State objects and, therefore, for the client to delegate to them. I introduced Factory, which ensures that there is only one instance of each State subclass, to ensure that the same instance is reused when moving back and forth through states.
public abstract class State { protected StateFactory _factory; protected IStateUser _context; public State(StateFactory factory, IStateUser context) { _factory = factory; _context = context; } protected void TransitionTo<T>(Func<T> creator) where T : State { State state = _factory.GetOrCreate<T>(creator); _context.CurrentState = state; } public abstract void MoveNext(); public abstract void MovePrevious(); } public class State1 : State { public State1(StateFactory factory, IStateUser context) : base(factory, context) { } public override void MoveNext() { TransitionTo<State2>(() => new State2(_factory, _context)); } public override void MovePrevious() { throw new InvalidOperationException(); } } public class State2 : State { public State2(StateFactory factory, IStateUser context) : base(factory, context) { } public override void MoveNext() { TransitionTo<State3>(() => new State3(_factory, _context));
Steve rowbotham
source share