When registering for Java events, duplicate listeners are usually allowed?

Should the addListener method check for duplicate registrations when called? If so, what should happen when a duplicate is found?

final public class exampleCanFire {
    public void addFooListener(FooListener listener) {
      // Before adding listener to private list of listeners, should I check for duplicates?
    }
}
+3
source share
4 answers

I prefer to store them in Listand not check for duplicates. Some advantages of this approach:

  • Listeners are notified in a deterministic manner and can potentially mark events as “consumed,” because of which they do not apply to subsequent listeners.
  • CopyOnWriteArrayList, ConcurrentModificationException ( ) ).
+4

, . , , . , , .

- , IllegalArgumentException , .

+3

, Set:

Set<FooListener> listeners = new HashSet<FooListener>();

public boolean addFooListener(FooListener listener) {
  return listeners.add(listener);
}
0

, , JAVA. , JAVA - . , j_random_hacker , , , , , , ? -)

0

Source: https://habr.com/ru/post/1715876/


All Articles