Good way to have a Collection Listener?

前端 未结 5 1119
梦谈多话
梦谈多话 2021-02-07 04:24

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

5条回答
  •  心在旅途
    2021-02-07 05:17

    You can using the ForwardingSet, ForwardingList, etc., from Guava 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 {
    
        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  Collection observedCollection(
        final Collection collection, final CollectionObserver observer) {
            return new Collection() {
                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
    
        };
        }
    

提交回复
热议问题