状态模式(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
相关推荐
Cc.Y32 分钟前
Java零基础入门:可变字符串与包装类:StringBuilder、StringBuffer 与 通讯录管理系统实战阿森_dev1 小时前
2027 届毕设选题怎么选:30 个 Java 方向选题的实现难度排序by209991 小时前
C++ 多态:同一个基类接口,调用不同的函数笔墨登场说说1 小时前
flink bin/start-cluster.sh 帮我做成开机启动Sarvartha1 小时前
Lambda 表达式和函数式接口kimloner1 小时前
开源一个 376KB 的 Windows 桌面小工具:便签 + 截图标注 + OCR + 待办提醒(C# / WinForms)小白学大数据1 小时前
拼多多反爬对抗实战:Scrapy 中间件化采集架构解析学逆向的2 小时前
win32注入代码阿松爱学习2 小时前
【Unity开发】Aspose.PDF的使用Sarvartha2 小时前
内部类知识