状态模式(State Pattern)
概念:
· 允许一个对象在内部状态发生改变时,改变它的行为;
· 把状态相关的行为放到独立的状态类里,通过切换状态对象来改变上下文行为;
· 目的是为了避免使用大量的if/else或switch判断状态;
UML结构:
┌─────────────────┐ │ StateBase │ ← 抽象状态 │ + Handle() │ └─────────────────┘ ▲ ▲ │ │ ┌─────────────────┐ ┌─────────────────┐ │ IdleState │ │ RunState │ ← 具体状态 │ + Handle() │ │ + Handle() │ └─────────────────┘ └─────────────────┘ ┌─────────────────────────┐ │ StateController │ ← 环境(上下文) │ - _currentState │ │ - _stateBases │ │ + ChangeState<T>() │ └─────────────────────────┘
代码示例:
cs/// <summary> /// 状态基类 /// </summary> public abstract class StateBase { public abstract void Handle(); } /// <summary> /// 待机状态 /// </summary> public class IdleState : StateBase { public override void Handle() { Console.WriteLine("进入Idle状态"); } } /// <summary> /// 奔跑状态 /// </summary> public class RunState : StateBase { public override void Handle() { Console.WriteLine("进入Run状态"); } } /// <summary> /// 状态控制类 /// </summary> public class StateController { private Dictionary<Type, StateBase> _stateBases = new(); // 状态映射表 private StateBase _currentState; // 当前状态 public StateController(StateBase currentState) { _stateBases.TryAdd(currentState.GetType(), currentState); this._currentState = currentState; _currentState.Handle(); } public void ChangeState<T>() where T : StateBase, new() { if (_stateBases.TryGetValue(typeof(T), out var state) && state != null) { _currentState = state; } else { _currentState = new T(); _stateBases.TryAdd(typeof(T), _currentState); } _currentState.Handle(); } } /// <summary> /// 客户端 /// </summary> public class Client { public static void Main() { StateController stateController = new(new IdleState()); stateController.ChangeState<RunState>(); } }
特点:
优点:· 代码更清晰,避免了大量 if/else 状态判断;
· 每个状态独立,修改和扩展容易;
· 符合开闭原则(新增状态时不用修改旧逻辑);
缺点:· 随着状态类的增加会导致系统复杂性随之增加;
适用场景:
· 对象的行为依赖于它的状态,并且在运行时可以改变行为;
· 游戏角色状态;
· 网络连接状态;
举例场景:
· 文档工作流(审批流):草稿 -> 审批中 -> 已通过 -> 已拒绝;
· 自动售卖机:待机 -> 投币 -> 选择商品 -> 出货 -> 找零;
【设计模式】状态模式
大飞pkz2025-09-29 13:50