python设计模式(状态模式)

学习版本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
    原文作者:去海里喂鱼
    原文地址: https://blog.csdn.net/u013346751/article/details/78467245
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞