原文:http://www.manew.com/thread-37511-1-1.html
接下来,我们继续我们的FSM有限状态机的设计,在设计三中我们实现了FSState这个类,我们继续实现FSEvent事件处理类。在FSEvent类里面我们声明了FiniteStateMachine里面定义的委托函数。代码如下:
protected FiniteStateMachine.EnterState mEnterDelegate;
protected FiniteStateMachine.PushState mPushDelegate;
protected FiniteStateMachine.PopState mPopDelegate;
同时我们定义了一个枚举用于处理有限状态机的状态,使用了System里面自带的封装的一个具有三个参数并返回TResult参数制定的雷兴志的方法。
public Func<object,object,object,bool> mAction = null;
这个FSEvent事件类也是独立的,不继承Mono。它的核心功能主要是处理FSState的Enter,Push,Pop。代码如下:
public FSState Enter(string stateName) {
mTargetState = stateName;
eType = EventType.ENTER;
return mStateOwner;
}
public FSState Push(string stateName) {
mTargetState = stateName;
eType = EventType.PUSH;
return mStateOwner;
}
public void Pop() {
eType = EventType.POP;
}
public void Execute(object o1,object o2,object o3) {
if (eType == EventType.POP) {
mPopDelegate();
}
else if (eType == EventType.PUSH) {
mPushDelegate(mTargetState, mOwner.CurrentState.StateName);
}
else if (eType == EventType.ENTER) {
mEnterDelegate(mTargetState);
}
else if (mAction != null) {
mAction(o1, o2, o3);
}
}
总的来说,FSEvent是通过调用Enter,Push,Pop,Execute执行状态的切换。下面把整个代码给大家展现一下:
using System;
public class FSEvent {
protected FiniteStateMachine.EnterState mEnterDelegate;
protected FiniteStateMachine.PushState mPushDelegate;
protected FiniteStateMachine.PopState mPopDelegate;
protected enum EventType { NONE, ENTER, PUSH, POP };
protected string mEventName;
protected FSState mStateOwner;
protected string mTargetState;
protected FiniteStateMachine mOwner;
protected EventType eType;
public Func<object,object,object,bool> mAction = null;
public FSEvent(string name, string target, FSState state, FiniteStateMachine owner, FiniteStateMachine.EnterState e, FiniteStateMachine.PushState pu, FiniteStateMachine.PopState po) {
mStateOwner = state;
mEventName = name;
mTargetState = target;
mOwner = owner;
eType = EventType.NONE;
mEnterDelegate = e;
mPushDelegate = pu;
mPopDelegate = po;
}
public FSState Enter(string stateName) {
mTargetState = stateName;
eType = EventType.ENTER;
return mStateOwner;
}
public FSState Push(string stateName) {
mTargetState = stateName;
eType = EventType.PUSH;
return mStateOwner;
}
public void Pop() {
eType = EventType.POP;
}
public void Execute(object o1,object o2,object o3) {
if (eType == EventType.POP) {
mPopDelegate();
}
else if (eType == EventType.PUSH) {
mPushDelegate(mTargetState, mOwner.CurrentState.StateName);
}
else if (eType == EventType.ENTER) {
mEnterDelegate(mTargetState);
}
else if (mAction != null) {
mAction(o1, o2, o3);
}
}
}
设计四把FSM常用的类已经封装好了,接下来我们会在
设计五
中去封装一个EventSystem类。用于处理事件的注册,分发等功能。