#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time :2022/5/23 9:48 @Author : @File :observer.py @Version :1.0 @Function:观察者模式/监听模式 """ """ 观察者基类 """ class ObserverBase: def update(self, observable, notifyData): """ 观察者收到通知后做对应的修改 @param observable: 被观察者对象(因为要在此方法里获取被观察者中的被观察数据 所以必须传被观察对象) @param notifyData: 通知的数据 @return: """ pass class ObservableBase: def __init__(self): # 观察者列表 self.__observerList = [] def addObserver(self, obServer): """ 添加观察者 @param obServer: 观察者对象 @return: """ self.__observerList.append(obServer) def delObserver(self, obServer): """ 删除观察者 @param obServer: 观察者对象 @return: """ self.__observerList.remove(obServer) def notifies(self, notifyData): """ 通知观察者 @param notifyData: 给观察者通知的数据 @return: """ for observer in self.__observerList: observer.update(self, notifyData) class Observable(ObservableBase): def __init__(self): super().__init__() # 被观察的数据 self.__value = None def getValue(self): return self.__value def setValue(self, value): self.__value = value self.notifies(f"当前值={self.__value}") class Observer1(ObserverBase): def update(self, observable, notifyData): if isinstance(observable, Observable) and observable.getValue() > 70: print(">70") class Observer2(ObserverBase): def update(self, observable, notifyData): if isinstance(observable, Observable) and 50 < observable.getValue() < 60: print("50<Num<60") class Observer3(ObserverBase): def update(self, observable, notifyData): if isinstance(observable, Observable) and observable.getValue() == 100: print("==100") if __name__ == '__main__': # 观察者 observe1 = Observer1() observe2 = Observer2() observe3 = Observer3() # 被观察者 observable = Observable() # 订阅通知 observable.addObserver(observe1) observable.addObserver(observe2) observable.addObserver(observe3) for i in range(101): observable.setValue(i)