Java:我自己的 API 中有哪些事件通知选项? [英] Java: What are my options for event notification in my own API?

查看:20
本文介绍了Java:我自己的 API 中有哪些事件通知选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您编写了一个 API,用于在独立线程实时收集数据.数据访问是线程安全的并通过接口进行.例如.getData() 不阻塞并提供最新信息.此 API 用于许多应用程序;一些 GUI 驱动,其他控制台程序.

Suppose you have an API you've written that collects data in real time in an independent thread. Data access is thread-safe and via an interface. E.g. getData() which does not block and provides the latest information. This API is used in a number of applications; some GUI driven, others console programs.

您有哪些选项可以通知您的应用程序有数据更新?我们绝对不希望 API 依赖于应用程序,因此我们不希望 fireTableDataChanged() 或来自 API 的任何类似内容.(在我们的 GUI 应用程序中,我们会在 API 通知我们或查看 API 后调用 fireTableDataChanged() 等.)

What options do you have to notify your application that there has been a data update? We definitely do not want the API to depend on the application, so we do not want to fireTableDataChanged() or anything like that from the API. (In our GUI application, we would call fireTableDataChanged() etc. after the API notifies us or we look at the API.)

非常感谢!

推荐答案

一种选择是编写您自己的事件生产者类.

One option is to write your own event producer class.

  • IEventListener<活动 >
  • IEventProducer, 事件>
  • 事件生产者, EVENT> 实现了 IEventProducer<听众,事件 >

IEventListener 由观察者实现.它有一个接收事件的方法.

IEventListener is implemented by the observers. It has a method for receiving an event.

IEventProducer 由任何 observable 通过 EventProducer 实现.它具有添加和删除侦听器的方法.

IEventProducer is implemented by any observable, via EventProducer. It has methods for adding and removing listeners.

EventProducer 是线程安全的.它具有将事件发送到侦听器的 CopyOnWriteArrayList 的方法.它捕获并记录侦听器抛出的任何异常.它还提供了添加和删除侦听器的方法.

EventProducer is thread-safe. It has a method for sending events to a CopyOnWriteArrayList of listeners. It catches and logs any exceptions thrown by listeners. It also provides methods for adding and removing listeners.

然后,任何 observable 类都可以通过内部 EventProducer 实现 IEventProducer.

Then, any observable class can implement IEventProducer via an internal EventProducer.

如果您尝试在同一个类上支持两种侦听器类型,则类型擦除将要求您为不同的侦听器命名不同的添加/删除侦听器方法.

If you try to support two listener types on the same class, type erasure will require that you name the add/remove listener methods differently for the different listeners.

这篇关于Java:我自己的 API 中有哪些事件通知选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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