Observer Pattern

Name: Observer Pattern

Alias: Subject Observer, Publish Subscribe, Callback.

Intent: Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

See:

On ExceptionHandling: Java Implementation: CeePlusPlus Implementation ScalaLanguage Paper


The two basic styles of notification: PushModel and PullModel. If the observed object does not have the necessary hooks for observers, the observers must rely on repeatedly polling the observed to note the changes. This is a "pull" versus a "push" type of pattern. Quite appropriate for certain applications.

A key tenet is that the observed does not know anything about the observers. It "publishes" a change and the observers get notified of the change.

The ObserverPattern is useful mostly for dynamic relationships between objects: you can hook up a new observer to an observable while the program is running (e.g. hook up a newly-opened viewing window to a domain object), then unhook it later (e.g. remove the window from the list of observers when the user closes it).

ObserverPattern is pretty low-level, and appears in its entirety as part of other important patterns (e.g. ModelViewController).

It is also the basis for publish-subscribe messaging architectures.

Additionally, ObserverMustNotChangeObservable.


I have thought about this some in the Publisher/Subscriber version, as follows:

Suppose the system has an EventHandler that wants to send out Notification X whenever this event occurs. You have a priority component, Component A, which is (probably) there all the time and may have to see this message right away. You also have a bunch of dynamic secondary components (B, C, and D) which may be there or not. They all have to receive the message sooner or later. Let's look at some possible scenarios:

Additionally, the Publisher can use a "Stay Current" mechanism to interrogate the Subscribers and find out if they are still there. If any subscriber disappears the Publisher drops him from the distribution list. There are many other permutations to this pattern.

-- MartySchrader


Other reference sources:


Contributors: ManuelSimoni, MartySchrader, RobbyRussell

CategoryPattern


EditText of this page (last edited October 16, 2010) or FindPage with title or text search