简体   繁体   English

注册和通知听众的实用程序?

[英]Utility for registering and notifying listeners?

I've used various kinds of listeners over the years.多年来,我使用了各种类型的听众。 Recently read the concurrency chapter in Josh Bloch's Effective Java where he talks about synchronizing adding and removing listeners, but recommends instead using CopyOnWriteArrayList /Set.最近阅读了 Josh Bloch 的Effective Java中的并发章节,他谈到了同步添加和删除侦听器,但建议改用CopyOnWriteArrayList /Set。

Recently I've used JMX MBean notifications.最近我使用了 JMX MBean 通知。 JMX provides a base class that you can extend, NotificationBroadcasterSupport , which provides the relevant methods for you: addNotificationListener, removeNotificationListener, sendNotification. JMX 提供了一个可以扩展的基础 class NotificationBroadcasterSupport ,它为您提供了相关的方法:addNotificationListener、removeNotificationListener、sendNotification。 In addition to the default constructor, there's one that takes an Exexutor which provides an easy way to make notifying listeners asynchronous.除了默认构造函数之外,还有一个使用 Exexutor 的函数,它提供了一种使通知侦听器异步的简单方法。 And presumably, this class internally uses something like CopyOnWriteArrayList internally to avoid synchronization issues (eg if listeners tries to remove itself from the list as part of its handleNotification method).据推测,这个 class 在内部使用了类似 CopyOnWriteArrayList 的东西来避免同步问题(例如,如果侦听器试图将自己从列表中删除作为其 handleNotification 方法的一部分)。

This makes me wonder if there are any general utilities for doing this.这让我想知道是否有任何通用实用程序可以做到这一点。 If I need a mechanism for registering and notifying listeners (that doesn't involve JMX), rather than roll my own using CopyOnWriteArrayList and possibly Executors and such, it would be good if there was a packaged, tested utility.如果我需要一种机制来注册和通知侦听器(不涉及 JMX),而不是使用 CopyOnWriteArrayList 和可能的 Executors 等来滚动我自己的机制,那么如果有一个打包的、经过测试的实用程序会很好。 Does anything like this exist in the JDK or common utility libs like Google's? JDK 或 Google 等通用实用程序库中是否存在类似的东西?

Yes, You can do this using Observer design pattern.是的,您可以使用观察者设计模式来做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM