#!/usr/bin/env python# -*- coding: utf-8 -*-__author__ = 'panda'# the publiser, toclass Subject(object): def __init__(self): self.__observers = [] # register a new obsever to the subject def register(self, observer): if observer not in self.__observers: self.__observers.append(observer) # remove a observer from the subject def remove(self, observer): try: self.__observers.remove(observer) except ValueError: print "observer not exist." def notify(self): print "notify" for observer in self.__observers: observer.update(self)# Example usageclass Data(Subject): def __init__(self, name): Subject.__init__(self) self.name = name self.temp = 0 self.humi = 0 self.press = 0.0 def set(self, temp, humi, press): self.temp = temp self.humi = humi self.press = press self.notify()class BoardA: def update(self, subject): print "当前观测值 temp: %d, humi: %d, press:%.1f" % (subject.temp, subject.humi, subject.press)class BoardB: def update(self, subject): print "统计观测值 avg temp:%d" % (subject.temp)class BoardC: def update(self, subject): print "其他 temp:%d" % (subject.temp)# Example usage...def main(): data = Data("panda") a = BoardA() b = BoardB() c = BoardC() data.register(a) data.register(b) data.register(c) data.set(20, 78, 101.325)if __name__ == '__main__': main()