制作一个聪明的听众发出通知,以避免code重复无处不在 [英] Making a smart listeners notifier to avoid code duplication everywhere
问题描述
注意:的code是线程安全的,换句话说,单线程的。只有我可以从听众的名单中删除自己。
ATTENTION: The code is thread-safe, in other words, single-threaded. Only I can remove myself from the list of listeners.
我有1000个不同听众的ArrayList,我不得不通知与code象下面这样:
I have 1000 different ArrayLists of listeners that I have to notify with code like below:
protected void onFlushed() {
int size = listeners.size();
for (int i = 0; i < size; i++) {
listeners.get(i).onFlushed();
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);
}
}
}
有一个聪明的方法来创建一个通知程序类,可以采取监听任何ArrayList中加上任何监听器方法,并执行下面的逻辑,我或我要重复code以上处处为每一个听众的方法?
Is there a smart way to create a Notifier class that can take any ArrayList of listeners plus any listener method and perform the logic below for me OR I have to duplicate the code above everywhere for every listener method?
我要求太多了从Java? :(
Am I asking too much from Java? :(
推荐答案
在当前的Java,有没有办法通过一个方法周围,你可以做一个函数式语言,但是你可以创建一个功能&LT;域名,范围和GT;
接口,并通过周围对象实现该接口
In current Java, there is no way to pass a method around, as you might do in a functional language, but you can create a Function<Domain, Range>
interface and pass around objects implementing that interface.
您可以考虑使用番石榴,它提供类似的东西功能成语和列表-COM prehension。
You might consider using Guava, which supplies something resembling functional idioms and list-comprehension.
这篇关于制作一个聪明的听众发出通知,以避免code重复无处不在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!