The Artima Developer Community
Sponsored Link

Event Generator Idiom
When and How to Make a Java Class Observable
by Bill Venners
First Published in JavaWorld, August 1998

<<  Page 3 of 10  >>


The event generator idiom

Enable interested objects (listeners) to be notified of a state change or other events experienced by an "event generator."

Also known as
Observer, Dependents, Publisher-Subscriber

One recent afternoon, I was sitting in my makeshift office at home, trying to think of a good example for explaining Java's event model in a Java class I was teaching. I was having trouble thinking of a decent example, when the phone rang. I got up, walked over to the phone, answered it, and had a short conversation. After I hung up, I realized I had my example.

What if, I asked myself, I had to design a software system that modeled a phone and all the objects that might be interested in knowing it was ringing? Certainly people in vicinity of the phone (i.e.,in the same room or house) might be interested in knowing it was ringing. In addition, an answering machine might want to know, as would a fax machine and a computer. Even a secret listening device may want to know, so it could surreptitiously monitor conversations.

I realized the interested parties might change as my program executed. For example, people might enter and leave the room containing the phone. Answering machines, computers, or top-secret listening devices might be attached to and detached from the phone as the program executed. In addition, new devices might be invented and added to future versions of the program.

So what's a good approach to designing this system? Answer: Make the telephone an event generator.

One or more objects (recipients) need to use information or be notified of state changes or events provided by another object (the information provider).

The problem
In Java, one object (the information provider) customarily sends information to another object (the recipient) by invoking a method on the recipient. But to invoke a method on the recipient, the information provider must have a reference to the recipient object. Furthermore, the type of that reference must be some class or interface that declares or inherits the method to invoke. In a very basic approach, the provider holds a reference to the recipient in a variable whose type is the recipient's class.

In the design context covered by this idiom, however, the basic approach of holding a reference to the recipient doesn't work so well. The requirements of this design context are:

The trouble with the basic approach is that the programmer has to know exactly what objects will be recipients when the information provider class is written. In this design context, however, the actual recipients may not be known until runtime.

<<  Page 3 of 10  >>

Sponsored Links

Copyright © 1996-2018 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use