制作一个智能的侦听器通知程序以避免到处重复代码 [英] Making a smart listeners notifier to avoid code duplication everywhere
问题描述
注意:代码是线程安全的,换句话说,是单线程的.只有我可以将自己从听众列表中删除.
ATTENTION: The code is thread-safe, in other words, single-threaded. Only I can remove myself from the list of listeners.
我有 1000 个不同的侦听器 ArrayList,我必须使用如下代码通知它们:
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 和任何侦听器方法,并为我执行下面的逻辑,或者我必须为每个侦听器方法在任何地方复制上面的代码?
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 中,无法像在函数式语言中那样传递方法,但您可以创建一个 域、范围>Function
接口并传递实现该接口的对象.
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.
您可以考虑使用 Guava,它提供了类似于功能习语和列表的内容-领悟.
You might consider using Guava, which supplies something resembling functional idioms and list-comprehension.
这篇关于制作一个智能的侦听器通知程序以避免到处重复代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!