Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Sponsored Links

Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs

The 'event generator' idiom

How and when to make a Java class observable

  • Print
  • Feedback

Page 4 of 5

// In file eventgui/ex1/AnsweringMachine.java
public class AnsweringMachine
    implements TelephoneListener {
    public void telephoneRang(TelephoneEvent e) {
        System.out.println("AM hears the phone ringing.");
    }
    public void telephoneAnswered(TelephoneEvent e) {
        System.out.println("AM sees that the phone was answered.");
    }
}
// In file eventgui/ex1/Person.java
public class Person {
    public void listenToPhone(Telephone t) {
        t.addTelephoneListener(
            new TelephoneAdapter() {
                public void telephoneRang(TelephoneEvent e) {
                    System.out.println("I'll get it!");
                }
            }
        );
    }
}


Note that AnsweringMachine implements the TelephoneListener interface directly. By contrast, the Person object instantiates an anonymous inner class that subclasses the TelephoneAdapter class. This anonymous inner class overrides the only method of interest to the Person object: telephoneRang().

The last class we need to define is an example application that will exercise all these classes and interfaces:

// In file eventgui/ex1/Example1.java
public class Example1 {
    public static void main(String[] args) { 
        Telephone ph = new Telephone();
        Person bob = new Person();
        AnsweringMachine am = new AnsweringMachine();
        ph.addTelephoneListener(am);
        bob.listenToPhone(ph);
        ph.ringPhone();
        ph.answerPhone();
    }
}


When executed, the Example1 application prints out:

The answering machine hears the phone ringing.
I'll get it!
The answering machine sees that the phone was answered.


Implementation guidelines
With the guidelines I list in this section, I am trying to define a default way to implement this idiom. I say default because, unless you have a specific reason to take a different implementation approach, you should automatically use the approach recommended in these guidelines. My theory is that if you adhere closely to the default implementation approach, it will be easier for your fellow programmers to recognize the idiom in your work. More importantly, I feel that such idiom recognition will make it easier for your fellow programmers to understand, use, and change your code.

On the other hand, you should feel free to depart from the default approach to implementing the idiom when you feel it makes sense. In fact, I myself describe two potential "variants" to the default approach in the next section.

Now, on to the guidelines:

  1. Create just one event object for each "firing" and pass it to all listeners.

  2. Make the event object immutable, so there is no possibility that a listener will change the event object as it propagates.

  3. Use a single thread to notify all listeners. In other words, the fire method should go through the list of listeners and invoke the appropriate handler method upon one listener after the other.

  4. Take a snapshot (clone the list) of registered listeners at the beginning of the firing process, then send the event to each listener registered at the time the snapshot was taken.

  5. Keep event handlers (listener methods) short. These methods should execute quickly because (in the default approach) listeners are notified one at a time. In other words, listeners must wait until all listeners before them in the queue have been notified, so it is good citizenship for listeners to be quick about handling events. If an event handler method really needs to do considerable work as a result of an event notification, consider designing the handler such that it fires off or notifies another thread that does the actual time-consuming work.

  6. Don't write listeners such that they depend on an order of notification.

  7. If a listener is not interested in all events that compose a particular event category, consider subclassing an adapter class and just overriding the methods of interest.


Variants
The following are variants to the default approach to implementing idioms:

  • Print
  • Feedback

Resources
  • Bill's next book is Flexible Java http://www.artima.com/flexiblejava/index.html
  • The discussion forum on event generators can be found at http://www.artima.com/flexiblejava/fjf/eventgen/index.html
  • Links to all previous Design Techniques articles http://www.artima.com/designtechniques/index.html
  • A description of the "I shall return" idiom, which describes a way to return multiple values from a Java method http://www.artima.com/flexiblejava/ishallreturn.html
  • Recommended books on Java design, including information on the Gang of Four's Design Patterns book http://www.artima.com/designtechniques/booklist.html
  • A transcript of an e-mail debate between Bill Venners, Mark Johnson (JavaWorld's JavaBeans columnist), and Mark Balbe on whether or not all objects should be made into beans http://www.artima.com/flexiblejava/comments/beandebate.html
  • Source packet that contains the example code used in this article http://www.artima.com/flexiblejava/code.html
  • A nice page that describes UML. http://www.holub.com/goodies/oo_design/uml.html
  • Object orientation FAQ http://www.cyberdyne-object-sys.com/oofaq/
  • 7237 Links on Object Orientation http://www.rhein-neckar.de/~cetus/software.html
  • The Object-Oriented Page http://www.well.com/user/ritchie/oo.html
  • Collection of information on OO approach http://arkhp1.kek.jp:80/managers/computing/activities/OO_CollectInfor/OO_CollectInfo.html
  • Design Patterns Home Page http://hillside.net/patterns/patterns.html
  • A Comparison of OOA and OOD Methods http://www.iconcomp.com/papers/comp/comp_1.html
  • Object-Oriented Analysis and Design MethodsA Comparative Review http://wwwis.cs.utwente.nl:8080/dmrg/OODOC/oodoc/oo.html
  • Patterns discussion FAQ http://gee.cs.oswego.edu/dl/pd-FAQ/pd-FAQ.html
  • Patterns in Java AWT http://mordor.cs.hut.fi/tik-76.278/group6/awtpat.html
  • Software Technology's Design Patterns Page http://www.sw-technologies.com/dpattern/
  • Previous Design Techniques columns http://www.javaworld.com/topicalindex/jw-ti-techniques.html