49 lines
1.1 KiB
Python
49 lines
1.1 KiB
Python
"""
|
|
实例:
|
|
一个任务状态机
|
|
"""
|
|
|
|
from abc import ABC, abstractmethod
|
|
|
|
class Task:
|
|
state: 'State'
|
|
def __init__(self):
|
|
self.set_state(PendingState())
|
|
|
|
def set_state(self, state: 'State'):
|
|
self.state = state
|
|
|
|
def handle(self):
|
|
self.state.handle(self)
|
|
|
|
|
|
# 状态接口
|
|
class State(ABC):
|
|
@abstractmethod
|
|
def handle(self, context):
|
|
pass
|
|
|
|
# 具体状态 - 待处理
|
|
class PendingState(State):
|
|
def handle(self, context):
|
|
print("任务待处理,开始处理任务...")
|
|
context.set_state(InProgressState())
|
|
|
|
# 具体状态 - 处理中
|
|
class InProgressState(State):
|
|
def handle(self, context):
|
|
print("任务处理中,完成任务...")
|
|
context.set_state(CompletedState())
|
|
|
|
# 具体状态 - 已完成
|
|
class CompletedState(State):
|
|
def handle(self, context):
|
|
print("任务已完成,无法再处理。")
|
|
|
|
if __name__ == "__main__":
|
|
print("============= 状态模式 =============")
|
|
task = Task()
|
|
task.handle()
|
|
task.handle()
|
|
task.handle()
|
|
print("\n=========== 状态模式结束 ===========") |