python状态模式和监听模式的对比

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u011747152/article/details/85774071
class Observer():
    def __init__(self):
        pass
    def behavior(self,water):
        pass
class Observable():
    def __init__(self):
        self.__observers=[]
    def addObserver(self,observer):
        self.__observers.append(observer)
    def removeObserver(self,observer):
        self.__observers.remove(observer)
    def notifyAll(self):
        for o in self.__observers:
            o.behavior(self)
class Water(Observable):
    def __init__(self):
        super().__init__()
        self.__temprature=25
    def setTemprature(self,temprature):
        self.__temprature=temprature
        self.notifyAll()
    def getTemprature(self):
        return self.__temprature
class Gas(Observer):
    def __init__(self):
        pass
    def behavior(self,water):
        if(water.getTemprature()>100):
            print("i'm gas")
class Liquid(Observer):
    def __init__(self):
        pass
    def behavior(self,water):
        if(water.getTemprature()<100 and water.getTemprature()>0):
            print("i'm liquid")
t=Water()
t.addObserver(Gas())
t.addObserver(Liquid())
t.setTemprature(200)
t.setTemprature(80)

在这里插入图片描述


class Context():
    def __init__(self):
        self.__states=[]
    def addState(self,state):
        self.__states.append(state)
    def setStateInfo(self,info):
        for o in self.__states:
            if(o.isMatch(info)):
                o.behavior()

class State():
    def __init__(self):
        pass
    def isMatch(self,info):
        pass
    def behavior(self):
        pass
class Gas(State):
    def __init__(self):
        pass
    def isMatch(self,info):
        if(info>100):
            print("i'm gas")
class Liquid(State):
    def __init__(self):
        pass
    def isMatch(self,info):
        if(info>0 and info <100):
            print("i'm liquid")
class Water(Context):
    def __init__(self):
        super().__init__()
        self.addState(Gas())
        self.addState(Liquid())
        self.__temprature=25
    def setTemprature(self,temprature):
        self.__temprature=temprature
        self.setStateInfo(temprature)
t=Water()
t.setTemprature(50)
t.setTemprature(202)

在这里插入图片描述

展开阅读全文

没有更多推荐了,返回首页