当前位置: 首页 > news >正文

2025--简单点--python之状态模式

一个context有可以切换多个state,切换到不同的state可以做不同的handle。
该模式将与状态相关的行为抽取到独立的状态类中, 让原对象将工作委派给这些类的实例, 而不是自行进行处理。

from__future__importannotationsfromabcimportABC,abstractmethodclassContext:""" The Context defines the interface of interest to clients. It also maintains a reference to an instance of a State subclass, which represents the current state of the Context. """_state=None""" A reference to the current state of the Context. """def__init__(self,state:State)->None:self.transition_to(state)deftransition_to(self,state:State):""" The Context allows changing the State object at runtime. """print(f"Context: Transition to{type(state).__name__}")self._state=state self._state.context=self""" The Context delegates part of its behavior to the current State object. """defrequest1(self):self._state.handle1()defrequest2(self):self._state.handle2()classState(ABC):""" The base State class declares methods that all Concrete State should implement and also provides a backreference to the Context object, associated with the State. This backreference can be used by States to transition the Context to another State. """@propertydefcontext(self)->Context:returnself._context@context.setterdefcontext(self,context:Context)->None:self._context=context@abstractmethoddefhandle1(self)->None:pass@abstractmethoddefhandle2(self)->None:pass""" Concrete States implement various behaviors, associated with a state of the Context. """classConcreteStateA(State):defhandle1(self)->None:print("ConcreteStateA handles request1.")print("ConcreteStateA wants to change the state of the context.")self.context.transition_to(ConcreteStateB())defhandle2(self)->None:print("ConcreteStateA handles request2.")classConcreteStateB(State):defhandle1(self)->None:print("ConcreteStateB handles request1.")defhandle2(self)->None:print("ConcreteStateB handles request2.")print("ConcreteStateB wants to change the state of the context.")self.context.transition_to(ConcreteStateA())if__name__=="__main__":# The client code.context=Context(ConcreteStateA())context.request1()context.request2()

output:
Context: Transition to ConcreteStateA
ConcreteStateA handles request1.
ConcreteStateA wants to change the state of the context.
Context: Transition to ConcreteStateB
ConcreteStateB handles request2.
ConcreteStateB wants to change the state of the context.
Context: Transition to ConcreteStateA

状态模式的优点

避免了过多的条件判断:状态模式通过将每个状态的行为封装到对应的类中,避免了在上下文中使用大量的条件判断语句(如if-else或switch-case)来根据状态执行不同的行为。

符合开闭原则:当需要增加新的状态时,只需要添加新的状态类,而不需要修改上下文类或其他状态类。
使状态转换更加明确:每个状态类只关心自己状态下的行为以及如何转换到其他状态,使得状态转换的逻辑更加清晰。

状态模式的缺点

  1. 增加了类的数量:每个状态都需要一个对应的类,可能会导致系统中类的数量增加。
  2. 状态转换逻辑分散:状态转换的逻辑分散在各个具体状态类中,可能会使得状态转换的整体逻辑不够直观。

适用场景

一个对象的行为取决于它的状态,并且它必须在运行时根据状态改变它的行为。
一个操作中含有大量的条件语句,且这些条件依赖于对象的状态。

通过状态模式,我们可以将复杂的条件判断转换为状态类之间的转换,使得代码更加清晰和可维护。

http://www.gsyq.cn/news/115497.html

相关文章:

  • ASMR音频高效获取终极指南:一键下载asmr.one海量内容
  • Obsidian Tasks插件:让知识库变身高效任务管理中心的终极指南
  • 大模型应用开发实战:从RAG踩坑到智能体优化,一篇搞定智能问答系统!
  • 开题报告新手工具:9大AI+步骤指南排名
  • Cesium 示例集:迁徙路网特效 glsl实现
  • buffctf_wp2
  • C4droid支持OpenGL,功能与限制你得知道
  • Label Studio多语言配置终极指南:三步完成界面本地化
  • 平板电脑语言设置在哪?咋添加切换?看这篇就懂
  • 开源敏捷协作平台完整教程:提升团队效率的终极指南
  • 开题报告PPT一键生成排名:9大平台+免费下载推荐
  • 跨境红海不迷路!多维战场布局技巧,助卖家逆势突围
  • Obsidian Linter完整使用指南:让你的笔记格式统一专业
  • TikTokDownload终极指南:一键下载抖音无水印视频的完整教程
  • IndexTTS2终极调优指南:释放语音合成全部潜力
  • 3步轻松搞定!yt-dlp-gui视频下载终极指南
  • EmotiVoice能否用于博物馆导览系统?文化语境适配
  • MegSpot:重新定义图片视频对比体验的完整解决方案
  • Label Studio国际化配置实战指南:从零构建多语言数据标注平台
  • 如何编写一个简单的服务器应用程序?
  • iPhone越狱完整教程:轻松解锁iOS设备全部潜能
  • 47、运维脚本与消息推送:从菜单到弹窗的全面指南
  • 如何配置一个!P地址和子网掩码?
  • 终极指南:5分钟掌握GroundingDINO配置选择黄金法则
  • 亲测灵活用工平台费用记账科目
  • Android BLE开发快速上手:5分钟环境搭建与实战避坑指南
  • 利用EmotiVoice构建多角色对话系统:剧本自动配音方案
  • Langflow终极指南:快速掌握AI工作流搭建的完整方案
  • 新能源知识库(163)马斯克的太空储能方案
  • 通杀级漏洞!任意用户密码重置挖掘实战:从原理到利用,小白也能上手