我有一个Sensor
状态机,我已经为其编写了Cycle()
方法:
/// <summary>
/// Cycle sets the machine to follow a path from one it's current state to the next. The
/// behavior of the sensor is to revert to it's default state should an invalid state be
/// encountered.
/// </summary>
/// <returns></returns>
public IState Cycle() {
if(_currentState.Next.IsNullOrEmpty()) {
_currentState = DefaultState.Set();
} else {
_currentState = _currentState.Cycle();
}
return _currentState;
}
public IEnumerator<IState> Cycle(Func<bool> HasWork) {
while(HasWork()) {
yield return Cycle();
}
}
执行:
[TestMethod]
public void SensorExperiment_CycleWhileFunc() {
float offset = .5f;
IState previousState = State.Empty;
IStimulus temp = new PassiveStimulus(68f) {
Offset = offset
};
ISensor thermostat = new Sensor(65f, 75f, temp);
int cycles = 0;
// using this func to tell the machine when to turn off
Func<bool> hasWork = () => {
previousState = thermostat.CurrentState;
// run 10 cycles6
return cycles++ < 10;
};
var iterator = thermostat.Cycle(hasWork);
while(iterator.MoveNext()) {
Console.WriteLine("Previous State: {0}\tCurrent State: {1}",
previousState.Name, iterator.Current.Name);
}
}
我已经阅读了Eric Lippert对使用 IEnumerator作为StateMachine 进行查询的回答。我的实现是否滥用或利用了 IEnumerator?我将我的实现视为提供一系列状态自动化的一种方式。