python設計模式之監聽模式

為不為發表於2019-01-02
class heatWater(object):
    def __init__(self):
        self.__observers=[]
        self.__waterHeater=25
    def addObserver(self,observer):
        self.__observers.append(observer)

    def getWatterHeater(self):
        return self.__waterHeater
    def heater(self,waterHeater):
        print(waterHeater)
        self.__waterHeater=waterHeater
        self.notify()
    def notify(self):
        for o in self.__observers:
            o.update(self)

class Observer(object):
    def update(self,heatHeater):
        pass

class DrinkWater(Observer):
    def update(self,heatHeater):
        if(heatHeater.getWatterHeater()>=100):
            print("drink")
class Shower(Observer):
    def update(self,heatHeater):
        if(heatHeater.getWatterHeater()<=70 and heatHeater.getWatterHeater()>=50):
            print("take shower")

t=heatWater()
t.addObserver(DrinkWater())
t.addObserver(Shower())
t.heater(70)
t.heater(100)
70
take shower
100
drink

現在是監聽模式寫死在物件裡,我們現在把他分離出來

class Observer(object):
    def update(self,heatHeater):
        pass
class Observable(object):
    def __init__(self):
         self.__observers=[]
    def addObserver(self,observer):
        self.__observers.append(observer)
    def notify(self):
        for o in self.__observers:
            o.update(self)

class heatWater(Observable):
    def __init__(self):
        super().__init__()
        self.__waterHeater=25
    def getWatterHeater(self):
        return self.__waterHeater
    def heater(self,waterHeater):
        print(waterHeater)
        self.__waterHeater=waterHeater
        self.notify()


class DrinkWater(Observer):
    def update(self,heatHeater):
        if(heatHeater.getWatterHeater()>=100):
            print("drink")
class Shower(Observer):
    def update(self,heatHeater):
        if(heatHeater.getWatterHeater()<=70 and heatHeater.getWatterHeater()>=50):
            print("take shower")

t=heatWater()
t.addObserver(DrinkWater())
t.addObserver(Shower())
t.heater(70)
t.heater(100)

在這裡插入圖片描述

相關文章