如果我有一个类似于状态机的类,Foo就是这样:
public class Foo
{
public virtual State Update()
{
switch (CurrentState)
{
case State.Start:
if (!WatingForData())
CurrentState = State.GotData;
break;
case State.GotData:
if (something else)
....
break;
}
return CurrentState;
}
}
处理一般步骤。
派生类Bar将为各个步骤提供另一个状态机 像这样:
public class Bar : Foo
{
public override State Update()
{
switch (CurrentState)
{
case State.GetData:
if (GotData())
CurrentState = State.GotData;
break;
case State.GotData:
if (ProcessData())
CurrentState = base.State.GotData;
break;
}
return CurrentState;
}
}
我想实现这样的目标;
while(!Foo.State == State.Done)
{
Thread.Sleep(10);
Foo.Update()
}
程序首先进入Bar.Update()并处理所有单个(子)步骤,完成后进入Foo.Update()。
鉴于我目前的代码,我必须将Foo的状态更改为new(而不是虚拟)并执行类似的操作;
while(!Foo.State == State.Done)
{
Thread.Sleep(10);
if(Bar.State == Bar.State.Done)
{
((Foo)Bar).Update()
}
else
{
Foo.Update();
}
}
不确定如何以更清洁的方式做到这一点。 我想知道是否有更好的方法来处理子状态的状态机? 举例非常感谢。
答案 0 :(得分:4)
您可以更改Bar.Update
以致电base.Update
:
public override State Update()
{
// sub steps:
switch (CurrentState)
{
case State.GetData:
if (GotData())
CurrentState = State.GotData;
break;
case State.GotData:
if (ProcessData())
CurrentState = base.State.GotData;
break;
}
// proceed to Foo.Update:
return base.Update();
}