news 2026/1/31 3:41:49

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

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
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. 状态转换逻辑分散:状态转换的逻辑分散在各个具体状态类中,可能会使得状态转换的整体逻辑不够直观。

适用场景

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

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

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/1/29 18:37:31

Java如何通过JNI实现调用C/C++代码,你知道吗?

在软件开发中,Java调用C/C代码是一项提升性能、复用遗留库的关键技术。其核心是通过Java本地接口(JNI)建立桥梁,让运行在JVM上的Java代码能够与本地机器码交互。理解其原理和正确使用方式,能帮助开发者解决纯Java难以处…

作者头像 李华
网站建设 2026/1/30 12:59:21

《深入理解 Ascend C:华为昇腾 AI 芯片的高性能编程语言》

引言:为什么需要 Ascend C?随着人工智能技术的飞速发展,算力需求呈指数级增长。传统通用处理器(如 CPU)在处理大规模神经网络计算时逐渐显现出性能瓶颈,而 GPU 虽然在并行计算方面表现优异,但其…

作者头像 李华
网站建设 2026/1/29 15:07:52

降AIGC率解读:10大工具+通俗说明推荐

降AIGC率解读:10大工具通俗说明推荐 �� 10大降AIGC工具核心对比速览 工具名称 处理速度 效果显著度 专业术语保留 适用场景 aibiye ⚡⚡⚡⚡ ⭐⭐⭐⭐ ✅✅✅ 高重复率论文紧急降重 aicheck ⚡⚡⚡ ⭐⭐⭐⭐ ✅✅✅✅ 法律/医学…

作者头像 李华
网站建设 2026/1/30 8:00:22

开源敏捷协作平台完整教程:提升团队效率的终极指南

你是否正在为项目管理效率低下而苦恼?传统工具无法满足敏捷团队需求,跨部门协作困难重重,任务进度跟踪犹如雾里看花。我们深知这些问题困扰着无数开发团队,今天将为你呈现开源敏捷协作平台的完整解决方案,助你彻底摆脱…

作者头像 李华
网站建设 2026/1/30 16:55:42

Inter字体家族:打造完美屏幕阅读体验的终极指南

Inter字体家族:打造完美屏幕阅读体验的终极指南 【免费下载链接】inter The Inter font family 项目地址: https://gitcode.com/gh_mirrors/in/inter Inter字体是专为数字屏幕设计的开源字体家族,以其卓越的可读性和优雅的几何风格,成…

作者头像 李华