When to use EventListenerList instead of a general collection of listeners

前端 未结 3 1957
谎友^
谎友^ 2021-02-19 15:52

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 th

相关标签:
3条回答
  • 2021-02-19 16:01

    There is no huge advantages this days. Just small optimizations. Here is what JavaDocs says:

    main benefits that this class provides are that it is relatively cheap in the case of no listeners, and it provides serialization for event-listener lists in a single place, as well as a degree of MT safety (when used correctly)

    With modern JVMs and collections it really doesn't matter. But what you could do with your own implementation is provide the way to fire changes on EDT if you using Swing - that would be beneficial.

    0 讨论(0)
  • 2021-02-19 16:05

    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.

    0 讨论(0)
  • 2021-02-19 16:05

    EventListenerList has a method, getListeners(Class<T> t), specifically for the case where you are only interested in one event type.

    Here's an example of how to use it:

    protected void fireChangeOccurred(Change change) {
        for (ChangeListener listener:
             listenerList.getListeners(ChangeListener.class)) {
                listener.stateChanged(new ChangeEvent(this));
        }
    }
    

    If you choose to maintain your own collection of listeners, I recommend a CopyOnWriteArrayList.

    0 讨论(0)
提交回复
热议问题