wj.*_*wj. 19 java collections listener observer-pattern
有没有更好的方法在java集合上拥有一个监听器,而不是将它包装在一个实现观察者模式的类中?
您可以使用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)
| 归档时间: |
|
| 查看次数: |
9703 次 |
| 最近记录: |