zoukankan      html  css  js  c++  java
  • 观察者模式

    最近考试有考过几次,便仔细瞧瞧了这是何物。

    我理解其中核心的点就在于,当一个观察者观察到发生了改变,不仅他自身要进行更新,其余所有的观察者都将被通知到并进行更新。

    代码实现如下:

    from abc import ABCMeta, abstractmethod
    
    
    class Subject(object):
        def __init__(self):
            self.observers = []
            self._state = ""
    
        @property
        def state(self):
            return self._state
    
        @state.setter
        def state(self, value):
            self._state = value
            self.notify_all()
    
        def add_observers(self, observer):
            self.observers.append(observer)
    
    
        def notify_all(self):
            for observer in self.observers:
                observer.update(self.state)
    
    
    
    class Observer(metaclass=ABCMeta):
    
        def __init__(self, subject):
            subject.add_observers(self)
    
    
        @abstractmethod
        def update(self, state):
            """all observers must implement this function to become a observer"""
    
    
    
    class RainObserver(Observer):
        def __init__(self, subject):
            super().__init__(subject)
    
        def update(self, state):
            print(self.__class__.__name__, "had updated! now state: ", state)
    
    
    class SunObserver(Observer):
        def __init__(self, subject):
            super().__init__(subject)
    
        def update(self, state):
            print(self.__class__.__name__, "had updated! now state: ", state)
    
    
    if __name__ == '__main__':
        tmp_subject = Subject()
    
        RainObserver(tmp_subject)
        SunObserver(tmp_subject)
    
        tmp_subject.state = "Rain"
    
        

    输出:

    RainObserver had updated! now state:  Rain
    SunObserver had updated! now state:  Rain
  • 相关阅读:
    Python Try Except
    Python 爬虫常用模块
    numpy中的数学
    机器学习名词
    numpy 矩阵变换transpose和swapaxes
    【Spark-core学习之四】 Spark任务提交
    【Spark-core学习之三】 Spark集群搭建 & spark-shell & Master HA
    【Spark-core学习之二】 RDD和算子
    【Spark-core学习之一】 Spark初识
    【Scala学习之二】 Scala 集合 Trait Actor
  • 原文地址:https://www.cnblogs.com/xu-xiaofeng/p/13636501.html
Copyright © 2011-2022 走看看