23种设计模式之状态模式
时间: 2023-12-02 16:40:39 浏览: 35
状态模式是一种行为型设计模式,它允许对象在内部状态改变时改变它的行为。这种模式通过将状态封装成独立的类来实现,使得状态转换变得更加清晰明确,并且可以让对象在不同状态下具有不同的行为。下面是一个简单的状态模式的示例:
```python
class State:
def do_action(self, context):
pass
class StartState(State):
def do_action(self, context):
print("Player is in start state")
context.state = self
class StopState(State):
def do_action(self, context):
print("Player is in stop state")
context.state = self
class Context:
def __init__(self):
self.state = None
def set_state(self, state):
self.state = state
def get_state(self):
return self.state
if __name__ == "__main__":
context = Context()
start_state = StartState()
start_state.do_action(context)
print(context.get_state())
stop_state = StopState()
stop_state.do_action(context)
print(context.get_state())
```
在上面的示例中,我们定义了一个状态接口`State`,并且实现了两个具体的状态类`StartState`和`StopState`。我们还定义了一个上下文类`Context`,它包含了一个状态对象,并且可以在不同的状态下执行不同的行为。在这个示例中,我们首先将状态设置为`StartState`,然后执行了`do_action`方法,输出了`Player is in start state`。接着我们将状态设置为`StopState`,再次执行`do_action`方法,输出了`Player is in stop state`。