2026/6/7 15:19:44
网站建设
项目流程
桂林行业网站,收录提交,中山发布微信公众号,公司网站设计基础任务书一个context有可以切换多个state#xff0c;切换到不同的state可以做不同的handle。
该模式将与状态相关的行为抽取到独立的状态类中#xff0c; 让原对象将工作委派给这些类的实例#xff0c; 而不是自行进行处理。
from __future__ import annotations
from abc import AB…一个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. _stateNone 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(fContext: Transition to{type(state).__name__})self._statestate self._state.contextself 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._contextcontext.setterdefcontext(self,context:Context)-None:self._contextcontextabstractmethoddefhandle1(self)-None:passabstractmethoddefhandle2(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.contextContext(ConcreteStateA())context.request1()context.request2()output:Context: Transition to ConcreteStateAConcreteStateA handles request1.ConcreteStateA wants to change the state of the context.Context: Transition to ConcreteStateBConcreteStateB handles request2.ConcreteStateB wants to change the state of the context.Context: Transition to ConcreteStateA状态模式的优点避免了过多的条件判断状态模式通过将每个状态的行为封装到对应的类中避免了在上下文中使用大量的条件判断语句如if-else或switch-case来根据状态执行不同的行为。符合开闭原则当需要增加新的状态时只需要添加新的状态类而不需要修改上下文类或其他状态类。使状态转换更加明确每个状态类只关心自己状态下的行为以及如何转换到其他状态使得状态转换的逻辑更加清晰。状态模式的缺点增加了类的数量每个状态都需要一个对应的类可能会导致系统中类的数量增加。状态转换逻辑分散状态转换的逻辑分散在各个具体状态类中可能会使得状态转换的整体逻辑不够直观。适用场景一个对象的行为取决于它的状态并且它必须在运行时根据状态改变它的行为。一个操作中含有大量的条件语句且这些条件依赖于对象的状态。通过状态模式我们可以将复杂的条件判断转换为状态类之间的转换使得代码更加清晰和可维护。