怎么自己开发网站,免费的网络营销方式,互联网营销推广怎么做,中铁建设集团有限公司梅洪亮Unity实现设计模式——状态模式
状态模式最核心的设计思路就是将对象的状态抽象出一个接口#xff0c;然后根据它的不同状态封装其行为#xff0c;这样就可以实现状态和行为的绑定#xff0c;最终实现对象和状态的有效解耦。
在实际开发中一般用到FSM有限状态机的实现然后根据它的不同状态封装其行为这样就可以实现状态和行为的绑定最终实现对象和状态的有效解耦。
在实际开发中一般用到FSM有限状态机的实现GF框架中的FSM和流程控制就是基于这个原理实现的。
1.State状态的抽象基类 public abstract class State{protected Context m_Context null;public State(Context theContext){m_Context theContext;}public abstract void Handle(int Value);}2.ConcreteStateAConcreteStateBConcreteStateC
状态State的子类 /// summary/// 状态A/// /summarypublic class ConcreteStateA : State{public ConcreteStateA(Context theContext) : base(theContext){ }public override void Handle(int Value){Debug.Log(ConcreteStateA.Handle);if (Value 10)m_Context.SetState(new ConcreteStateB(m_Context));}}/// summary/// 状态B/// /summarypublic class ConcreteStateB : State{public ConcreteStateB(Context theContext) : base(theContext){ }public override void Handle(int Value){Debug.Log(ConcreteStateB.Handle);if (Value 20)m_Context.SetState(new ConcreteStateC(m_Context));}}/// summary/// 状态C/// /summarypublic class ConcreteStateC : State{public ConcreteStateC(Context theContext) : base(theContext){ }public override void Handle(int Value){Debug.Log(ConcreteStateC.Handle);if (Value 30)m_Context.SetState(new ConcreteStateA(m_Context));}}3.Context
Context类-持有目前的状态,并将相关信息传给状态 public class Context{State m_State null;public void Request(int Value){m_State.Handle(Value);}public void SetState(State theState){Debug.Log(Context.SetState: theState);m_State theState;}}4.测试代码 public class StatePatternExample5 : MonoBehaviour{void Start(){UnitTest();}void UnitTest(){Context theContext new Context();theContext.SetState(new ConcreteStateA(theContext));theContext.Request(5);theContext.Request(15);theContext.Request(25);theContext.Request(35);}}