using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Sog; namespace Operation { public class Transition { 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 { public Dictionary StateHandlerTable; public List> TransMachine; public T State; public FiniteStateMachine(T initState, Dictionary handlerTable, List> 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 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 FindTransition(V m) { Transition ret = null; foreach (Transition trans in TransMachine) { if (trans.current.Equals(State) && trans.msg.Equals(m)) { ret = trans; break; } } return ret; } } }