注册Java事件时,通常允许重复的侦听器? [英] When registering for Java events, are duplicate listeners typically allowed?

查看:108
本文介绍了注册Java事件时,通常允许重复的侦听器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

应该在调用add方法时检查重复的注册?如果是这样,当发现重复时应该怎么办?

Should an 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?
    }
}


推荐答案

我的偏好是将它们存储在列表中,而不是检查重复项。这种方法的一些优点:

My preference is to store them in a List and not check for duplicates. Some advantages of this approach:


  • 监听器以确定性顺序通知,可能将事件标记为消耗,导致不传播到

  • 可以使用 CopyOnWriteArrayList 实现,它允许侦听器在通知回调期间自动删除而不使用 ConcurrentModificationException 被抛出(这是非常重要,并且是编写面向事件的代码时的经典支持)。

  • Listeners are notified in a deterministic order and could potentially mark events as "consumed" causing them not to propagate to subsequent listeners.
  • One can use the CopyOnWriteArrayList implementation, which allows a listener to remove itself during a notification callback without a ConcurrentModificationException being thrown (this is very important and is a classic gotcha when writing event oriented code).

这篇关于注册Java事件时,通常允许重复的侦听器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆