Observer Pattern

Yesterday I was reading some article about AOP and OOP concepts. Article has some discussion about Observer pattern, then I thought lets read about this first and then move further. I found this small example and one line definition on wiki which helped me.
In observer pattern “one or more objects (called observers or listeners) are registered (or register themselves) to observe an event which may be raised by the observed object (the subject). (The object which may raise an event generally maintains a collection of the observers.)”.

I always like the learn from practicals rather than to read tons for theory pages. Following is the the small code which cleared my concepts about this pattern :

Simple Pseudo code for Observer Pattern In Python :

class Listener:

def initialise (self, subject):

subject.register(self)

def notify (self, event):

event.process()

class Subject:

def initialise (self):

self.listeners = []

def register (self, listener):

self.listeners.append(listener)

def unregister (self, listener):

self.listeners.remove(listener)

def notify_listeners (self, event):

for listener in self.listeners:

listener.notify(event)
subject = Subject()

listenerA = Listener()

listenerB = Listener()

subject.register(listenerA)

subject.register(listenerB)

#the subject now has two listeners registered to it.

Leave a Comment

"Quote of the Day"