当前位置: 首页 > 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.jsqmd.com/news/104663/

相关文章:

  • 2025实验室气路施工品牌核心维度评测报告:实验室气路设计、实验室气路设计规范、科研院所实验室气路、高校实验室气路、实验室气路安装 - 优质品牌商家
  • 髋关节翻修double switch手术,你了解多少?
  • OpenWrt网络加速神器:TurboACC让你的路由器性能翻倍
  • Taiga 终极指南:免费开源项目管理工具的完整应用方案
  • 基于Gradle8.0的插件开发
  • 使用pe修改电脑密码的办法
  • EmotiVoice与RVC结合使用指南:实现更精细的声音定制
  • ASMR音频高效获取终极指南:一键下载asmr.one海量内容
  • Obsidian Tasks插件:让知识库变身高效任务管理中心的终极指南
  • Windows XP系统启动出现登录对话框的原因及解决办法
  • 大模型应用开发实战:从RAG踩坑到智能体优化,一篇搞定智能问答系统!
  • 基于Vue3和Element Plus构建现代化后台管理系统架构实践
  • Java如何通过JNI实现调用C/C++代码,你知道吗?
  • 开题报告新手工具:9大AI+步骤指南排名
  • Cesium 示例集:迁徙路网特效 glsl实现
  • Label Studio多语言配置终极指南:三步完成界面本地化
  • C4droid支持OpenGL,功能与限制你得知道
  • 平板电脑语言设置在哪?咋添加切换?看这篇就懂
  • 开源敏捷协作平台完整教程:提升团队效率的终极指南
  • ExoPlayer实时流媒体播放:从入门到精通的完整指南
  • Python中append()方法的使用、原理及效率解析
  • 开题报告PPT一键生成排名:9大平台+免费下载推荐
  • buffctf_wp2
  • 跨境红海不迷路!多维战场布局技巧,助卖家逆势突围
  • 嵌入式都能用上的gdb调试进阶--下
  • 专业级FreeMarker模板在线调试平台:实时验证语法与逻辑的终极解决方案
  • Obsidian Linter完整使用指南:让你的笔记格式统一专业
  • AutoUnipus智能学习工具终极指南:3步实现自动化高效学习
  • TikTokDownload终极指南:一键下载抖音无水印视频的完整教程
  • IndexTTS2终极调优指南:释放语音合成全部潜力