You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

86 lines
2.4 KiB

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Sog;
namespace Operation
{
public class Transition<T, V>
{
public T current;
public V msg;
public T next;
};
public delegate void ActionHandler(Object obj);
//public delegate void ActionHandler(long, long);
//T 状态类型
//V 消息类型
//使用方法
//构造函数传入 初始状态 状态迁移表 和 状态处理表
//然后调用ChangeState
public class FiniteStateMachine<T, V>
{
public Dictionary<T, ActionHandler> StateHandlerTable;
public List<Transition<T, V>> TransMachine;
public T State;
public FiniteStateMachine(T initState, Dictionary<T, ActionHandler> handlerTable, List<Transition<T, V>> transMachine)
{
State = initState;
StateHandlerTable = handlerTable;
TransMachine = transMachine;
}
public void ChangeState(V m, Object obj)
{
ActionHandler actHandler = FindAction(m);
if (actHandler == null)
{
TraceLog.Error("FiniteStateMachine.ChangeState error not find action current = {0} message = {1}", State, m);
return;
}
actHandler(obj);
}
private ActionHandler FindAction(V m)
{
Transition<T, V> trans = FindTransition(m);
if (trans == null)
{
TraceLog.Error("FiniteStateMachine.FindAction error not find trans current = {0} message = {1}", State, m);
return null;
}
State = trans.next;
ActionHandler actHandler = null;
StateHandlerTable.TryGetValue(State, out actHandler);
if (actHandler == null)
{
TraceLog.Error("FiniteStateMachine.FindAction error not find handler state = {0} message={1}", State, m);
return null;
}
return actHandler;
}
private Transition<T, V> FindTransition(V m)
{
Transition<T, V> ret = null;
foreach (Transition<T, V> trans in TransMachine)
{
if (trans.current.Equals(State) && trans.msg.Equals(m))
{
ret = trans;
break;
}
}
return ret;
}
}
}