news 2026/4/16 17:48:28

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/4/16 11:59:05

数字人Live2D实战体验:从零打造专属虚拟伙伴的完整指南

数字人Live2D实战体验:从零打造专属虚拟伙伴的完整指南 【免费下载链接】awesome-digital-human-live2d Awesome Digital Human 项目地址: https://gitcode.com/GitHub_Trending/aw/awesome-digital-human-live2d 想要拥有一个能够智能对话、表情丰富的数字人…

作者头像 李华
网站建设 2026/4/16 13:40:38

KITTI-360数据集:自动驾驶技术研究的终极解决方案

KITTI-360数据集:自动驾驶技术研究的终极解决方案 【免费下载链接】kitti360Scripts This repository contains utility scripts for the KITTI-360 dataset. 项目地址: https://gitcode.com/gh_mirrors/ki/kitti360Scripts KITTI-360数据集是一个专门为自动…

作者头像 李华
网站建设 2026/4/16 12:04:52

shell编程基础:自动化备份及错误异常处理方法

shell脚本是将多个命令组织成程序、实现自动化任务的核心工具。它不仅是Linux/Unix系统管理员的基本功,也广泛应用于开发、测试和日常运维中,能显著提升工作效率和操作的可靠性。掌握shell编程,意味着你能够将重复性劳动交给机器,…

作者头像 李华
网站建设 2026/4/16 10:41:41

PM2 WebUI:告别命令行,可视化Node.js应用管理的终极方案

PM2 WebUI:告别命令行,可视化Node.js应用管理的终极方案 【免费下载链接】pm2-webui PM2 WebUI. Opensource Alternative to PM2 Plus. Minimalistic App Manager and Log Viewer 项目地址: https://gitcode.com/gh_mirrors/pm/pm2-webui 还在为复…

作者头像 李华
网站建设 2026/4/16 2:48:32

探索开源机械臂:低成本智能自动化创新实践

在当今技术快速发展的时代,开源机械臂正以革命性的方式重塑机器人技术的应用边界。对于想要深入了解DIY机器人的新手和普通用户来说,Faze4六轴机械臂提供了一个绝佳的入门平台,让每个人都能以经济实惠的方式探索智能控制方案的无限可能。 【免…

作者头像 李华
网站建设 2026/4/16 12:11:40

EmotiVoice语音合成在心理治疗语音日记中的正向引导作用

EmotiVoice语音合成在心理治疗语音日记中的正向引导作用 在快节奏、高压力的现代生活中,越来越多的人面临情绪困扰与心理健康挑战。传统的心理咨询受限于资源稀缺、成本高昂和隐私顾虑,难以覆盖广泛人群。而数字疗法的兴起,尤其是基于AI的智…

作者头像 李华