1.状态抽象类AbstractState
public abstract class AbstractState
{
public abstract void OnChangeState();
}
为了简单 只写一个抽象方法,在状态改变时触发
==============================
2.状态实现类IdleState
public class IdleState : AbstractState
{
public override void OnChangeState()
{
Debug.Log("静止动作");
}
}
==============================
3.状态实现类MoveState
public class MoveState : AbstractState
{
public override void OnChangeState()
{
Debug.Log("移动动作");
}
}
==============================
4.状态实现类NoneState
public class NoneState : AbstractState
{
public override void OnChangeState
{
//Do Something
}
}
==============================
5.状态枚举StateEnum
public enum StateEnum
{
Idle,
Move,
None,
}
==============================
6.状态机StateMachine
public class StateMachine
{
//用于保存枚举和状态实例
private Dictionary<StateEnum,AbstractState> stateDic;
//用于保存前一个状态枚举
public StateEnum prevStateEnum = StateEnum.None;
//用于保存当前状态枚举
public StateEnum currentStateEnum = StateEnum.None;
//用于保存当前状态
private AbstractState currentState;
public StateMachine()
{
Init();
}
private void Init()
{
if(stateDic == null)
{
stateDic = new Dictionary<StateEnum,AbstractState>();
stateDic.Add(StateEnum.None, new NoneState());
stateDic.Add(StateEnum.Idle, new IdleState());
stateDic.Add(StateEnum.Move, new MoveState());
}
}
public void ChangeState(StateEnum state)
{
if(currentStateEnum != StateEnum.None)
{
prevStateEnum = currentState;
}
currentState = GetState(state);
currentStateEnum = state;
currentState.OnChangeState();
}
//如果需要连续撤回多次 则使用栈或者列表存储 根据需求而定
public void ChangeToPrevious()
{
if(prevStateEnum != StateEnum.None)
{
currentStateEnum = prevStateEnum;
prevStateEnum = StateEnum.None;
}
currentState = GetState(currentStateEnum);
currentState.OnChangeState();
}
private AbstractState GetState(StateEnum state)
{
if(stateDic.ContainsKey(state))
{
return stateDic[state];
}
throw new Exception("Cannot find state");
return null;
}
}
==============================
7.使用实例
class Player
{
private StateMachine stateMachine;
public Player()
{
stateMachine = new StateMachine();
}
//按键按下时
public void OnKeyDown()
{
stateMachine.ChangeState(StateEnum.Move);
}
//按键抬起时
public void OnKeyUp()
{
stateMachine.ChangeStatae(StateEnum.Idle);
}
}
==============================
状态模式最大的优势就是让代码的条理变得清晰,以状态机的状态管理逻辑作为依托,实现状态的稳定切换。