Observer pattern
Key 1: Spreading information to all listeners.
This is the basic pattern in which an object tells other objects about something interesting. It is very useful in GUI applications, pub/sub applications, and those applications where we need to notify a lot of loosely-coupled application components about a change occurring at one source node. In the following code, Subject
is the object to which other objects register themselves for events via register_observer
. The observer
objects are the listening objects. The observers
start observing the function that registers the observers
object to Subject
object. Whenever there is an event to Subject
it cascades the event to all observers
:
import weakref class Subject(object): """Provider of notifications to other objects """ def __init__(self, name): self.name = name self._observers = weakref.WeakSet() def register_observer(self, observer): """attach the observing object for this subject...