Presents your JAVA E-NEWSLETTER for November 7, 2002 <-------------------------------------------> REUSE THE JAVA.UTIL.OBSERVABLE CLASS It's common to roll your own Listener/Event systems, but there is a pre-existing generic solution in the standard Java libraries that can save you a lot of work. While the use of Events and Listeners is common in the Java libraries, they are all just examples of the Observer pattern. The Java Util package provides an Observable/Observer combination, which, while not as powerful as having a specific Event and Listener, is still useful in many circumstances. The following three classes demonstrate a way to use the Observer/Observable classes. import java.util.*; public class OEventManager extends Observable { static public void main(String[ ] args) { OEventManager mgr = new OEventManager( ); mgr.addObserver( new OListener( ) ); mgr.addObserver( new OListener( ) ); mgr.addObserver( new OListener( ) ); mgr.fireChange("Changed. "); } public void fireChange(String msg) { setChanged( ); notifyObservers( new OEvent(msg)); } } class OListener implements Observer { public void update(Observable o, Object arg) { System.err.println("Passed '"+arg+"' by "+o+" to "+this); } } class OEvent extends EventObject { public OEvent(String msg) { super(msg); } } An important aspect to note is that the OEvent class is storing the message in the source. Usually this would be the object that the event occurred upon, and the message would be kept in a separate field, but the example is being kept concise. Also notice the use of setChanged--Observable, which doesn't notify observers if the Observable has not changed; instead it will quietly ignore the call to notifyObservers. The example outputs the following: Passed 'OEvent[source=Changed. ]' by OEventManager@c9a to OListener@3b63e6 Passed 'OEvent[source=Changed. ]' by OEventManager@c9a to OListener@25cf3e Passed 'OEvent[source=Changed. ]' by OEventManager@c9a to OListener@48f0cd Because the Observer interface forces the update(Observable,Object) method signature upon you, the Observer/Observable classes are not a replacement for defining your own Event/Listener classes; they are a useful tool when that interface is acceptable. ----------------------------------------