我有一个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);
}
}
我已将IEnumerator用作StateMachine的查询已阅读Eric Lippert's answer。我的实现是滥用还是利用IEnumerator?我将自己的实现视为提供一系列状态自动化的一种方式。
最佳答案
我不认为像这样使用它真的是一种滥用,毕竟,您最多会将结果视为一个集合。
另一方面,我看不出您为什么要在此处使用迭代器的任何原因。如果将代码重写为以下内容,则其工作原理应相同。
while (hasWork())
Console.WriteLine("Previous State: {0}\tCurrent State: {1}",
previousState.Name, thermostat.Cycle().Name);