构建状态机 [英] Building a state machine
本文介绍了构建状态机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在为项目创建状态机。该项目将有许多算法,每个算法都有一个状态机。返回下一个状态的枚举会污染基类枚举,所以不是真的很激动。
下面是我提出的工作代码。对于返回类型的对象并不是很疯狂但是没有真正看到它的方法。
任何人都有任何想法?
我尝试过:
I'm looking at creating a state machine for a project. The project will have many algorithms each having a state machine in it. Returning an enumeration for the next state would pollute a base class enumeration, so not really thrilled about that.
Below is working code that I came up with. Not crazy about the return type of object but don't really see a way around it.
Anyone have any thoughts?
What I have tried:
using System;
namespace StateMachine
{
///
public class StateMachine2BaseClass
{
protected void RunAlgorithm(Func<object> nextState)
{
while (nextState != null)
{
var currentState = nextState;
nextState = (Func<object>)currentState();
}
}
protected Func<object> End()
{
return null;
}
}
///
public class StateMachine2 : StateMachine2BaseClass
{
private int count;
public void Run()
{
RunAlgorithm(Start);
}
private Func<object> Start()
{
Console.WriteLine("Start");
return Step_1;
}
private Func<object> Step_1()
{
if (++count > 5)
return Step_2;
Console.WriteLine("Step 1");
return Step_1;
}
private Func<object> Step_2()
{
Console.WriteLine("Step 2");
return End;
}
}
}
推荐答案
正如F-ES Sitecore建议的那样,基于类方法可以更好地工作。
定义一个抽象的State类,它声明一个抽象的DoWork方法,将机器信息类作为参数,描述状态将运行的信息,如果有的话,并返回一个状态实例。
然后,对于您需要的每个状态,定义一个从State类派生的新类,并为每个实现DoWork方法。
所有你要做的就是:
As F-ES Sitecore suggests, a class - based approach would work better.
Define an abstract State class which declares an abstract DoWork method, taking as a parameter the "machine info" class which describes the information the states will operate on, if any and returning a State instance.
Then for each state you need, define a new class derived from the State class and implement the DoWork method for each.
All you have to do then is:
protected void RunAlgorithm(Func<object> nextState)
{
State currentState = new FirstState();
while (currentState != null)
{
currentState = currentState.DoWork(machineInfo);
}
}
系统将整理出每次需要调用的DoWork方法。
The system will sort out which DoWork method it needs to call each time.
这篇关于构建状态机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文