news 2026/9/5 23:05:01

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/9/5 22:16:41

Arduino CAN库实战指南:从入门到精通CAN总线通信

Arduino CAN库实战指南:从入门到精通CAN总线通信 【免费下载链接】arduino-CAN An Arduino library for sending and receiving data using CAN bus. 项目地址: https://gitcode.com/gh_mirrors/ar/arduino-CAN 还在为嵌入式设备间的可靠通信而烦恼吗&#x…

作者头像 李华
网站建设 2026/9/6 8:14:05

【GESP】C++三级真题 luogu-B4414 [GESP202509 三级] 日历制作

GESP C 2025年9月三级真题,一维数组考点,难度★★☆☆☆。 luogu-B4414 [GESP202509 三级] 日历制作 题目要求 题目题解详见:https://www.coderli.com/gesp-3-luogu-b4414/ https://www.coderli.com/gesp-3-luogu-b4414/https://www.coder…

作者头像 李华
网站建设 2026/9/4 23:26:06

Cesium 示例集:迁徙路网特效 glsl实现

🚀 个人简介:某大型测绘遥感企业资深Webgis开发工程师,软件设计师(中级)、CSDN优质创作者 💟 作 者:柳晓黑胡椒❣️ 📝 专 栏:再识Cesium 🌈 若有帮助,还请关注 ➕ 点赞➕收藏,不行的话我再努努力💪💪💪 基于 Cesium 的迁徙路网特效 GLSL 实现 迁徙路网特效…

作者头像 李华
网站建设 2026/9/5 18:51:49

为何渴望被赞赏?过度求赞有何影响?如何建立健康评价体系?

追求他人的认可,本质是渴望在外部镜像中确认自我价值。这不仅是一种普遍的社会心理,也是许多焦虑与内耗的根源。理解“被赞赏”的驱动力,才能更理性地对待外界的评价,建立更稳固的自我内核。 为什么我们如此渴望被他人赞赏 这种渴…

作者头像 李华
网站建设 2026/9/5 17:04:53

AriaNg GUI完整指南:免费跨平台下载管理器终极解决方案

AriaNg GUI完整指南:免费跨平台下载管理器终极解决方案 【免费下载链接】aria-ng-gui 一个 Aria2 图形界面客户端 | An Aria2 GUI for Windows & Linux & MacOS 项目地址: https://gitcode.com/gh_mirrors/ar/aria-ng-gui AriaNg GUI是一款功能强大的…

作者头像 李华
网站建设 2026/9/5 9:19:44

macOS终极网络共享方案:HoRNDIS驱动程序完全配置指南

在移动办公日益普及的今天,如何将Android设备的网络快速、稳定地共享到Mac电脑上成为许多用户的迫切需求。HoRNDIS驱动程序正是解决这一痛点的专业工具,通过USB数据线将Android手机变身为网络设备,为macOS用户提供无缝的网络连接体验。 【免费…

作者头像 李华