美文网首页
python 观察者模式

python 观察者模式

作者: 假程序员 | 来源:发表于2020-09-14 21:00 被阅读0次
import abc
import threading


class Observer(object):
    __metaclass__ = abc.ABCMeta

    @abc.abstractmethod
    def work(self):
        pass


class ClientA(Observer):
    def work(self):
        print(type(self))


class ClientB(Observer):
    def work(self):
        print(id(self))


class Subject(object):
    def __init__(self):
        self.observers = list()
        self.lock = threading.RLock()

    def register_observer(self, observer):
        self.lock.acquire()
        if observer not in self.observers:
            self.observers.append(observer)
        self.lock.release()

    def un_register_observer(self, observer):
        self.lock.acquire()
        if observer in self.observers:
            self.observers.remove(observer)
        self.lock.release()

    def notify(self):
        self.lock.acquire()
        for _ in self.observers:
            _.work()
        self.lock.release()


if __name__ == '__main__':
    subject = Subject()
    a = ClientA()
    b = ClientB()
    subject.register_observer(a)
    subject.register_observer(b)
    subject.notify()

相关文章

  • 观察者模式_20190912(python)

    一、观察者模式介绍 二、观察者模式UML 三、python实现观察者模式(demo1、2) 1、demo1 """...

  • 2017-12-26

    今天黄老师讲解了python观察者模式,观察者模式有很多实现方式,从根本上说,该模式必须包含两个角色:观察者和被观...

  • 2017-12-27

    今天上午黄老师主要讲解他的项目,用python讲解了观察者模式。实现观察者模式的时候要注意,观察者和被观察对象之间...

  • python设计模式

    观察者模式 python观察者模式是一种设计模式需求:员工上班在偷偷看股票,拜托前台一旦老板进来,就通知他们,让他...

  • Python观察者模式

    [python|高级篇|笔记|设计模式|观察者模式] 这两天读了[Head First设计模式][1]和[Pyth...

  • 12.27

    今天老师主要还是讲解他的项目 依然用python讲解了观察者模式。观察者模式就是有一块公共数据中心(函数),各个模...

  • 11.9设计模式-观察者模式-详解

    设计模式-观察者模式 观察者模式详解 观察者模式在android中的实际运用 1.观察者模式详解 2.观察者模式在...

  • 2017年12月27日学习总结

    今天上午黄老师主要还是讲解他的项目 依然用python讲解了观察者模式。观察者模式就是有一块公共数据中心(函数),...

  • RxJava基础—观察者模式

    设计模式-观察者模式 观察者模式:观察者模式(有时又被称为发布(publish )-订阅(Subscribe)模式...

  • 前端面试考点之手写系列

    1、观察者模式 观察者模式(基于发布订阅模式) 有观察者,也有被观察者。 观察者需要放到被观察者列表中,被观察者的...

网友评论

      本文标题:python 观察者模式

      本文链接:https://www.haomeiwen.com/subject/msdtyktx.html