This might be a little long question but i try to keep it as small as possible and try to put it in the best way i can.
I have reading about design patterns and found observer pattern very intresting. i searched for its practical application and found various answers here. one of those answer was:
Whenever a question is posted, all the subscribers following the topics of similar interest are notified.
i tried to model this system in python as below:
using Mongoengine ORM to model a User and define a function notify for the User class which can be used to notify a user:
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
I know the trivial way it can be done but can I do something better by using observer pattern here?
NOTE: I am not trying to fit the problem to the design pattern as it is usually frowned upon. I am just trying to implement it for *learning purpose. I have tried searching for some implementations but unsuccessful so far
MY QUESTION : I presented the way I know I could have approached the problem(pseudocode above) but is there anything that can be done better using an observer pattern here?