是什么?
允许对象在其内部状态改变时改变其行为。通过将状态相关的行为封装到独立的类中,状态模式可以简化状态转换逻辑,提高代码的可扩展性和可维护性。
核心组成部分
- 上下文(Context):维护当前状态的实例,并定义客户端感兴趣的接口。
- 状态接口(State):声明所有具体状态类需要实现的方法。
- 具体状态(ConcreteState):实现状态接口,定义特定状态下的行为和状态转换逻辑。
代码示例
模拟一个 咖啡机 的工作过程:
咖啡机 有多个状态,比如:
- 待机状态(Idle):等待用户操作。
- 准备咖啡状态(Brewing):正在制作咖啡。
- 维护状态(Maintenance):机器需要清理或者水、咖啡豆不足。
根据不同的状态,咖啡机的行为会有所不同。例如:
- 在待机状态下,你可以选择启动咖啡制作。
- 在准备咖啡状态下,按按钮不会有反应,因为机器正在工作。
- 在维护状态下,机器可能会提示你“加水”或者“清洁”。
用状态模式实现咖啡机:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| from abc import ABC, abstractmethod
class CoffeeMachineState(ABC): @abstractmethod def handle_request(self, coffee_machine: 'CoffeeMachine'): pass
class IdleState(CoffeeMachineState): def handle_request(self, coffee_machine: 'CoffeeMachine'): print("咖啡机处于待机状态,等待用户选择...") coffee_machine.set_state(BrewingState())
class BrewingState(CoffeeMachineState): def handle_request(self, coffee_machine: 'CoffeeMachine'): print("咖啡机正在制作咖啡,请稍候...") coffee_machine.set_state(IdleState())
class MaintenanceState(CoffeeMachineState): def handle_request(self, coffee_machine: 'CoffeeMachine'): print("咖啡机需要维护,请加水或清理滤网...") coffee_machine.set_state(IdleState())
class CoffeeMachine: def __init__(self): self._state = IdleState()
def set_state(self, state: CoffeeMachineState): self._state = state
def request(self): self._state.handle_request(self)
if __name__ == "__main__": coffee_machine = CoffeeMachine() coffee_machine.request() coffee_machine.request()
coffee_machine.set_state(MaintenanceState()) coffee_machine.request()
|
运行结果
1 2 3
| 咖啡机处于待机状态,等待用户选择... 咖啡机正在制作咖啡,请稍候... 咖啡机需要维护,请加水或清理滤网...
|
核心组成部分和咖啡机的例子可以这样对应:
- 上下文(Context)
1 2 3 4 5 6 7 8 9 10
| class CoffeeMachine: def __init__(self): self._state = IdleState()
def set_state(self, state: CoffeeMachineState): self._state = state
def request(self): self._state.handle_request(self)
|
CoffeeMachine 就是上下文。它保存了当前状态(self._state),并通过 request() 方法调用当前状态的行为。同时,它允许通过 set_state() 切换状态。
- 状态接口(State)
状态接口的作用:
• 定义了所有状态需要实现的方法(行为)。
• 是所有具体状态类的公共父类,确保上下文能够一致地调用状态行为。
1 2 3 4
| class CoffeeMachineState(ABC): @abstractmethod def handle_request(self, coffee_machine: 'CoffeeMachine'): pass
|
- 具体状态(ConcreteState)
具体状态的作用:
• 是状态接口的实现类。
• 定义了该状态下的具体行为逻辑。
• 负责状态之间的切换。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| class IdleState(CoffeeMachineState): def handle_request(self, coffee_machine: 'CoffeeMachine'): print("咖啡机处于待机状态,等待用户选择...") coffee_machine.set_state(BrewingState())
class BrewingState(CoffeeMachineState): def handle_request(self, coffee_machine: 'CoffeeMachine'): print("咖啡机正在制作咖啡,请稍候...") coffee_machine.set_state(IdleState())
class MaintenanceState(CoffeeMachineState): def handle_request(self, coffee_machine: 'CoffeeMachine'): print("咖啡机需要维护,请加水或清理滤网...") coffee_machine.set_state(IdleState())
|
在代码中,IdleState, BrewingState, 和 MaintenanceState 是具体状态类:
• 它们实现了状态接口 CoffeeMachineState。
• 每个类定义了该状态下的行为(例如打印提示、状态转换等)。
• 它们在某些条件下通过 coffee_machine.set_state() 切换状态。