这可能有点长,但我尽量保持它尽可能小,并尝试以最佳方式将其放入。使用观察者模式来为订阅者建模通知
我有阅读关于设计模式,发现观察者模式非常intresting。我搜索了它的实际应用,并找到各种答案here。其中一个答案是:
每当发布问题时,都会通知跟踪相似主题的所有订阅者。
我试图如低于此系统在Python建模:使用Mongoengine ORM建模一个用户和定义一个函数通知为可用于通知用户的用户类
:
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
我知道琐碎的方式是可以做到的,但我可以做一些通过这里使用观察者模式更好?
注意:我不是试图将问题适应设计模式,因为它通常是皱眉。我只是想实现它为*学习目的。我试图寻找一些实现,但不成功到目前为止
我的问题:我提出的,我知道我可以走近这个问题(上述伪代码),但这样有什么,可以在这里使用观察者模式来实现更好?
感谢您的回复。现在我可以至少看到关于事情如何粘在一起的更大的图片,但是,我有一个小小的怀疑。对于任何大中型应用程序或流行的Web服务,我们可能会有很多用户说50万个例子。现在将所有论坛用户始终保存在内存中的列表中是有意义的吗?将新用户添加到数据库时会发生什么? – anekix
你说得对,把他们留在记忆里很可能是不合理的。在这种情况下,您可以保留其id的引用,并且只有在主题需要通知订阅者时才将其加载到内存中。有些'persistence'框架可以在调用时通过'Lazy Loading'把对象存储到内存中来为你处理。请参阅https://en.wikipedia.org/wiki/Lazy_loading – gimg1