views:

399

answers:

4

Is there a better way to have a listener on a java collection than wrap it in a class implementing the observer pattern ?

+1  A: 

Well, if you don't actually need a java.util.Collection or List instance, you could use a DefaultListModel. I'm not aware of any "real" Collection implementations with builtin listener/observer support.

Michael Borgwardt
+2  A: 

Apache Events.

"Commons-Events provides additional classes for firing and handling events. It focusses on the Java Collections Framework, providing decorators to other collections that fire events."

John Ellinwood
Should be noted that this is still a sandbox project. An interesting one however.
BalusC
+7  A: 

You should check out Glazed Lists

It contains observable List classes, which fire events whenever elements are added, removed, replaced, etc

Chi
Agreed. GlazedLists is excellent.
Barend
+1  A: 

You can using the ForwardingSet, ForwardingList, etc., from Google Collections http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/ForwardingCollection.html to decorate a particular instance with the desired behavior.

Here's my own implementation that just uses plain JDK APIs:

// create an abstract class that implements this interface with blank implementations
// that way, annonymous subclasses can observe only the events they care about
public interface CollectionObserver<E> {

    public void beforeAdd(E o);

    public void afterAdd(E o);

    // other events to be observed ...

}

// this method would go in a utility class
public static <E> Collection<E> observedCollection(
    final Collection<E> collection, final CollectionObserver<E> observer) {
        return new Collection<E>() {
            public boolean add(final E o) {
             observer.beforeAdd(o);
             boolean result = collection.add(o);
             observer.afterAdd(o);
             return result;
            }

            // ... generate rest of delegate methods in Eclipse

    };
    }
LES2