首先,我有点担心大部分代码似乎都在以一种不太安全的方式处理并发问题。考虑对访问相同侦听器列表的任何代码进行一些锁定。这样,您可以将此代码简化为:
protected void onFlushed() {
synchronized(listeners) {
for (FlushListener listener : listeners) {
listener.onFlushed();
}
}
}
在您的代码周围重复这并不是太糟糕。话虽如此,如果出于某种原因您需要那里的逻辑,您可以创建一个类似这样的类:
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
public class Notifier<T> {
public static interface NotificationRunnable<T> {
public void notify(T t);
}
private ArrayList<T> listeners;
public Notifier() {
listeners = new ArrayList<T>();
}
public void addListener(T t) {
listeners.add(t);
}
public void notifyAll(NotificationRunnable<T> nr) {
int size = listeners.size();
for (int i = 0; i < size; i++) {
nr.notify(listeners.get(i));
int newSize = listeners.size();
if (newSize == size - 1) {
size--;
i--;
} else if (newSize != size) {
throw new ConcurrentModificationException("List was altered while iterating! oldSize=" + size + " newSize=" + newSize);
}
}
}
}
然后调用它的代码如下所示:
Notifier<FlushListener> notifier = new Notifier();
notifier.addListener(new FlushListener());
public void onFlushed() {
notifier.notifyAll(new NotificationRunnable<FlushListener>(){
public void notify(FlushListener t) {
t.onFlushed();
}
});
}
甚至在实际方法中将其简化为一行:
NotificationRunnable<FlushListener> flushRunnable = new NotificationRunnable<FlushListener>(){
public void notify(FlushListener t) {
t.onFlushed();
}
}
public void onFlushed() {
notifier.notifyAll(flushRunnable);
}