何时使用EventListenerList而不是一般的收听器集合 [英] When to use EventListenerList instead of a general collection of listeners
问题描述
当我学习如何在Java中触发事件时,我熟悉了EventListenerList。当我创建自己的监听器时,我编写监听器,所以它扩展了EventListener,我将它们存储在一个EventListenerList中,我的fire方法将通过这样的事件监听器:
When I learned how to fire events in Java, I became familiar with EventListenerList. When I create my own listeners, I write the listener so it extends EventListener, I store them in an EventListenerList, and my fire method would go through the event listeners like this:
protected void fireChangeOccurred(Change change) {
Object[] listeners = listenerList.getListenerList();
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==ChangeListener.class) {
((ChangeListener)listeners[i+1]).changeOccurred(change);
}
}
}
现在我正在审核代码只要将侦听器放入HashMap(可以是任何集合),监听器接口就不会扩展EventListener,并且fire方法如下所示:
Now I'm reviewing code that simply puts listeners into a HashMap (could be any collection), the listener interface does not extend EventListener, and the fire method looks like this:
protected void fireChangeOccurred(Change change) {
for (ChangeListener listener : listeners) {
listener.changeOccurred(change);
}
}
替代使用EventListenerList有什么好处?只是维护我自己的监听器列表?它是否真的只关心监听器是否在一个Swing组件 - 事件调度线程是否重要?
What are the advantages of using EventListenerList instead of just maintaining my own list of listeners? Does it really only matter if the listeners are in a Swing component - does it matter for the Event Dispatch Thread?
推荐答案
对我来说, EventListenerList
的主要优点是如果类具有(或可能拥有)多个类型的监听器。许多Swing组件都做;你正在审查的一个可能不是。第二个例子较短,但它具有隐式设计限制。
To me, the major advantage of EventListenerList
is if the containing class has (or may have) more than one type of listener. Many Swing components do; the one you're reviewing may not. The second example is shorter, but it has that implicit design limitation.
这篇关于何时使用EventListenerList而不是一般的收听器集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!