(NOTE: I updated this post after realizing a few mistakes of my own so this isn't the original but a more refined one instead)
For this purpose I'd do two new interfaces, ListListener
and Listenable
and then I would create a new class like ListenableArrayList
which would wrap every List
method with a call to one (or more) relevant methods defined in ListListener
. In code it'd be something like this:
public class ListenableArrayList<T> extends ArrayList<T>
implements Listenable<T> {
private ArrayList<T> internalList;
private ListListener<T> listener;
/* .. */
public void add(T item) {
listener.beforeAdd(T item);
internalList.add(item);
listener.afterAdd(T item);
}
/* .. */
public void setListener(ListListener<T> listener) {
this.listener = listener;
}
}
public interface ListListener<T> {
/* .. */
void beforeAdd(T item);
void afterAdd(T item);
/* .. */
}
public interface Listenable<T> {
/* .. */
void setListener(ListListener<T> listener);
/* .. */
}
The reason I'd do it this way would be to allow for creating truly ad-hoc listeners on the fly instead of tying the ListenableArrayList to some specific implementation. For example with this the following would be possible:
Listenable<String> list = new ListenableArrayList<String>();
list.setListener(new ListListener<String>() {
@Override
public void beforeAdd(String item) {
System.out.println("About to add element "+item+"...");
}
@Override
public void afterAdd(String item) {
System.out.println("...element "+item+" has been added.");
}
});
A bit cluttered, maybe but on the other hand this would allow for easy extension to Collections, Sets and whatnot rather easily.