Presents your JAVA E-NEWSLETTER for January 13, 2003 <-------------------------------------------> IMPLEMENT EVENT/LISTENER EASILY WITH THE NOTIFIER CLASS The Event/Listener pattern in Java is a common one, and very useful, but implementing your own pattern can be time consuming and tedious. Each time you have to deal with the List or Vector, you also have to deal with the Add method, the Remove method, and then to finish it all off, you have to iterate over the list to inform all the listeners. It would be nice to simply code: Notifier notifier = new Notifier("actionPerformed"); ... notifier.addListener( someObject ); ... notifier.notify( new ActionEvent(this) ); Just a few lines of code and everything else would be done for you. The Notifier Class below does just this: package com.generationjava.lang; import java.util.*; import java.lang.reflect.*; public class Notifier { private ArrayList listeners = new ArrayList(); private String listenerMethod; public Notifier(String name) { this.listenerMethod = name; } public void addListener(Object not) { this.listeners.add(not); } public void removeListener(Object not) { this.listeners.remove(not); } public void notify(EventObject event) { Iterator itr = listeners.iterator(); while(itr.hasNext()) { try { Object listener = itr.next(); Class clss = listener.getClass(); Method method = clss.getMethod( this.listenerMethod, new Class[] { event.getClass() } ); method.invoke( listener, new Object[] { event } ); } catch(Exception e) { e.printStackTrace(); } } } } It's not optimized for performance, and it's not synchronized, but it is quick to develop under and saves time when creating Event/Listener APIs. By using the Notifier Class, you can perform a common task without having to code it each time. ----------------------------------------