有没有更好的方法在java集合上拥有一个侦听器,而不是把它包装在一个实现观察者模式的类中?
发布于 2009-12-22 04:04:37
你应该看看Glazed Lists
它包含可观察的列表类,每当添加、删除、替换等元素时都会触发事件
发布于 2009-12-22 04:05:50
您可以使用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
};
}
发布于 2009-12-22 03:55:58
Commons- events为触发和处理事件提供额外的类。它专注于Java集合框架,为触发事件的其他集合提供装饰器。
https://stackoverflow.com/questions/1942144
复制相似问题