3

我有一个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?我将我的实现视为提供一系列状态自动化的一种方式。

4

1 回答 1

2

我不认为这样使用它真的是一种滥用,毕竟你把结果当成一个集合。

另一方面,我看不出你应该在这里使用迭代器的任何理由。如果您将代码重写为以下内容,它应该可以正常工作。

while (hasWork())
    Console.WriteLine("Previous State: {0}\tCurrent State: {1}",
       previousState.Name, thermostat.Cycle().Name);
于 2012-06-10T17:17:18.240 回答