状态模式(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
相关推荐
meilindehuzi_a4 小时前
从零理解并实现 RAG:用 LangChain.js 构建语义检索问答系统风流 少年4 小时前
Julia江畔柳前堤4 小时前
GO01-Go 语言与主流编程语言深度对比:-)5 小时前
算法-归并排序GIS阵地6 小时前
QgsRasterDataProvider 完整详解(QGIS 3.40.13 C++)yaoxin5211237 小时前
462. Java 反射 - 获取声明类与封闭类阿里嘎多学长7 小时前
2026-07-14 GitHub 热点项目精选ttod_qzstudio7 小时前
【软考设计模式】备忘录模式:对象状态的捕获与无损恢复精讲ttod_qzstudio8 小时前
【软考设计模式】责任链模式:请求传递的多级处理与发送接收解耦精讲charlie1145141918 小时前
Cinux: 为大内核铺路