Wednesday, December 30, 2009

Generics for Event Listener Pattern

To workaround the somethingListener -> somethingEvent mapping.

I'm not the first person to care about Event Notification. (but it's a problem that I'd rather not care about, especially after I met Qt's Signals and Slots... Java beaten by C++? Come on!)
    Maybe we can use Java 5 generics to save some code...
    // Common interface for all listeners. 
    public interface Listener<E> {
      public void notify(E event);
    }
    
    public class PedalEvent {
      // any custom properties wherever necessary
    }
    
    public class PedalListener implements Listener<PedalEvent> {
      public void notify(PedalEvent event) {
         // ... implementation ... 
      } 
    } 
    
    public class Car {
      public void addPedalListener(Listener<PedalEvent> pedalListener); 
      public void removePedalListener(Listener<PedalEvent> pedalListener); 
    } 
    
    
    What do you think?