拥有Collection Listener的好方法?

wj.*_*wj. 19 java collections listener observer-pattern

有没有更好的方法在java集合上拥有一个监听器,而不是将它包装在一个实现观察者模式的类中?

Chi*_*Chi 13

你应该看看釉面列表

它包含可观察的List类,无论何时添加,删除,替换元素等,都会触发事件


les*_*es2 6

您可以使用Guava中ForwardingSet,ForwardingList等来装饰具有所需行为的特定实例.

这是我自己的实现,只使用普通的JDK API:

// 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

    };
    }
Run Code Online (Sandbox Code Playgroud)