Skip to content

Instantly share code, notes, and snippets.

@kishore-devaraj
Created November 25, 2017 18:17
Show Gist options
  • Save kishore-devaraj/d5184dfa39696e0b0baf6c13f0433208 to your computer and use it in GitHub Desktop.
Save kishore-devaraj/d5184dfa39696e0b0baf6c13f0433208 to your computer and use it in GitHub Desktop.
Observer Design Pattern Template
# Observer Design Pattern is mainly used in scenarios when there is a change in the Class attributes
# which should be reflected to all of its objects. This technique is explained with the help of Podcast
# example. Here whenever new podcast is uploaded, it should notify all the subscribers.
class Podcast(object):
def __init__(self,subscriber_name):
self.subscriber_name = subscriber_name
def get_podcast(self):
return self._podcasts
def add_podcast(self,podcast_name):
self._podcasts.add(podcast_name)
def delete_podcast(self,podcast_name):
self._podcasts.remove(podcast_name)
# This where we actually implement the observer desing pattern logic
# We create a set called _podcasts which contains all the podcast that
# has been uploaded and its acts a global object to all instance of
# this class
def __new__(cls):
if not hasattr(cls,'_podcasts'):
cls._podcasts = set()
return super(Podcast,cls).__new__(cls)
def __name__ == '__main__':
# Creating three users (Admin and two subscribers)
admin = Podcast('admin')
kishore = Podcast('kishore')
devaraj = Podcast('devaraj')
# Now the admin adds few podcasts to the Podcast Class
admin.add_podcast("Bitcoin and its future")
admin.add_podcast("Writing Idomatic Python")
# Now each client who has subscribed to that podcast we receive
# these podcasts in the respective object instances.
kishore.get_podcast()
# {'Bitcoin and its future','Writing Idomatic Python'}
devaraj.get_podcast()
# {'Bitcoin and its future','Writing Idomatic Python'}
# Similarly whenever the admin delete a existing a podcast
# it will be deleted from all the instances.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment