Observer

Intent

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

      -Design Patterns, GoF

 

Not long ago my clutch gave out, so I had my Jeep towed to a local dealership.  I didn’t know anybody at the dealership, and none of them knew me, so I gave them my telephone number so they could notify me with an estimate.  That arrangement worked so well we did the same thing when the work was finished.  Because this all turned out perfectly for me, I suspect the service department at the dealership employs the same pattern with most of its customers.

      -David Geary, Javaworld.com

 

Questions

1) Is there any difference between the Observer pattern and an Event Listener?

2) Does there need to be an association from the Observer to the Subject?    

3) What are the performance implications of using a synchronous listener?  Would you want to notify asynchronously?

4) Would an observer ever need to receive updates from more than one subject?  How could this be accomplished?

5) Who should be responsible for calling the Notify method?

6) What are the push and pull models of the Observer pattern?  What implications do they have for reusability?

7) What is a Change Manager and how does it help?

8) Why are anonymous inner classes good for being Observers?

9) How can an Observer “veto” the change event?  When is this a good thing?

10) Under what conditions do you use an observer?

 

Examples – Which are Observers?

1) Swing Event and Change Listeners

2) java.util’s Observer and Observable

3) Caching

 

Implement It!

The Discovery Channel has hired you to build a special piece of software for the Tour de France cycling team.  The main function of the software is to notify the riders of major race events (e.g. crashes, lead changes, etc.) via their wireless bike computers.  Would the Observer pattern work for this problem?

 

References

·         Speaking on the Observer Pattern, Tony Sintes (Javaworld.com)

·         An Inside View of the Observer, David Geary (Javaworld.com, March 2003)

·         Exploring the Observer Design Pattern, Doug Purdy (Microsoft.com, January 2002)