2.5. The Observer Pattern

The GOF book defines the intent of the observer pattern as being to define a one-to-many relationship between objects so that when the state of an object changes, all its dependents are notified.

The relationships among objects in the observer pattern are described in terms of subjects and observers. Subjects can have any number of dependent observers. Observers are notified whenever the subject undergoes a change in state. In response, each observer queries the subject to synchronize its state with the subject's state.

This relationship is also described as a publisher-subscriber relationship: the subject publishes notifications and the observers subscribe to be notified of these changes. This arrangement allows the subject to notify its subscribers without having to know who they are.

ActionScript has an implementation of this pattern in its event listener model. Chances are you have done something like the following pseudo-code:

someObject.addEventListener(MouseEvent.CLICK,someFunction);
someObject.addEventListener(MouseEvent.CLICK,someOtherFunction);

In this example someObject would have to directly extend the EventDispatcher class (http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/events/EventDispatcher.html) or some class that extends it in its ancestor chain.

In this case someObject is the subject or publisher and someFunction and someOtherFunction are the observers or subscribers. When someObject is clicked, the dispatchEvent function ...

Get Professional Cairngorm™ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.