使用观察者模式为订阅者建模通知

时间:2017-10-06 14:37:11

标签: python design-patterns observer-pattern

这可能是一个有点长的问题,但我尽量保持尽可能小,并尝试以最好的方式把它放在一边。

我已阅读有关设计模式的内容,并发现观察者模式非常有趣。我搜索了它的实际应用并找到了各种答案here。其中一个答案是:

  

每当发布问题时,都会通知所有关注相似主题的订阅者。

我试图在python中对此系统进行建模,如下所示:

使用Mongoengine ORM用户建模,并为User类定义函数 notify ,可用于通知用户:

from mongoengine import *

connect('tumblelog')


# User model
class User(Document):
        email = StringField()
        first_name = StringField()
        last_name = StringField()
        topic_subscribed = StringField()

        def notify(self):
                print "email sent to user :{} {} {}".format(self.first_name, self.last_name, self.email)
                print "user was subsacribed to: {}".format(self.topic_subscribed)






# simulate publishing of an article of a particular topic
while True:
        x = raw_input(">>>")
        print "question of {} topic published".format(x)

        # How to notify all users that are subscribed to the topic ?????
        # naive way :
        # def some_aynchronous_function():
        #       1) find all users from db that are subscribed to the topic
        #       2) notify each user by looping through all of them          

我知道可以做到的琐碎方式,但我可以在这里使用观察者模式做些更好的事情吗?

注意:我并不是试图将问题纳入设计模式,因为它通常不赞成。我只是想为 *学习目的实现它。我已经尝试搜索一些实现但到目前为止不成功

我的问题:我提出了我可以解决问题的方式(上面的伪代码),但是在这里使用观察者模式可以做得更好吗?

1 个答案:

答案 0 :(得分:0)

  

观察者模式是一个软件设计模式,其中一个对象,   称为主题,维护其受抚养人名单,称为   观察者,并自动通知他们任何状态变化,   通常通过调用他们的方法之一。

来源:Wikipedia - Observer Pattern

您的ObserverUser,但您仍然需要定义Subject,在您的情况下,Topic可能会被称为subscribers。本主题将在内部列表中保留其所有class Topic: subscribers = [] def addSubscriber(self, subscriber): subscribers.append(subscriber) def notifySubscribers(self): for subscriber : subscribers: subscriber.notify(self) 的列表。然后,当发生更新时,主题将通过遍历每个订阅者并调用他们的某些方法来通知所有订阅者。例如:

(void)setValuesForKeysWithDictionary()
相关问题