学习版本3.5.2
#学习版本3.5.2
#状态模式定义:允许一个对象在其内部状态改变时改变它的行为。
#举例子:灯泡的开关
class LightState(object):
def display(self):
pass
class StateOn(LightState):
def action(self, light):#开灯状态下按开关
print("light off")
light.setState(StateOff())
class StateOff(LightState):
def action(self, light):#关灯状态下按开关
print("light on")
light.setState(StateOn())
class Light(object):
def __init__(self, state):
self.state = state
def setState(self, state):
self.state = state
#按开关
def pressSwith(self):
self.state.action(self)
if __name__ == "__main__":
stateoff = StateOff()
li = Light(stateoff)
li.pressSwith()
li.pressSwith()
li.pressSwith()
li.pressSwith()
运行结果
light on
light off
light on
light off