状态模式是一种行为设计模式,用于解决对象在不同状态下具有不同行为
在对象行为根据对象状态而改变时,规避使用大量的条件语句来判断对象的状态,提高系统可维护性
- #!/usr/bin/env python
- # -*- coding: UTF-8 -*-
- __doc__ = """
- 状态模式
- 例:水在不同温度下状态也会不同
- """
-
- from abc import ABC, abstractmethod
-
-
- class State(ABC):
- """状态基类"""
-
- @abstractmethod
- def handle(self, temperature):
- pass
-
-
- class SolidState(State):
- """具体状态类"""
-
- def handle(self, temperature):
- if temperature < 0:
- return "冰"
-
-
- class LiquidState(State):
- """具体状态类"""
-
- def handle(self, temperature):
- if 0 <= temperature < 100:
- return "液态水"
-
-
- class GaseousState(State):
- """具体状态类"""
-
- def handle(self, temperature):
- if temperature >= 100:
- return "水蒸气"
-
-
- class Water:
- """上下文类(水)"""
-
- def __init__(self):
- self.state = LiquidState()
-
- def change_state(self, state):
- self.state = state
-
- def get_state(self, temperature):
- return self.state.handle(temperature)
-
-
- if __name__ == '__main__':
- """
- 水在 25 摄氏度时为:液态水
- 水在 -5 摄氏度时为:冰
- 水在 105 摄氏度时为:水蒸气
- """
- water = Water()
- print(f"水在 25 摄氏度时为:{water.get_state(25)}")
-
- water.change_state(SolidState())
- print(f"水在 -5 摄氏度时为:{water.get_state(-5)}")
-
- water.change_state(GaseousState())
- print(f"水在 105 摄氏度时为:{water.get_state(105)}")