3

我正在为我的系统构建一个 API,它接收 UDP 消息并解析它们。现在我需要通知开发人员这些更改。

目前我有两种实现方式,但我不确定哪一种更好,以及是否还有其他选择。

解决方案 A ArrayBlockingQueue

它似乎在空闲时不消耗任何功率。在 API 方面,当我想通知新的更改时,我会创建一个静态数组并向其中添加消息。因此,在开发人员方面,我可以将它放在一个线程中以侦听任何新消息。用户将获取消息,检查其类型和属性等。

解决方案 B 回调

我相信这个解决方案会更漂亮,更有条理。我只需创建一个包含所有可能通知类型的接口,然后开发人员就可以实现这个接口。在 API 方面,我有一个相同侦听器的哈希图,以便 API 可以通知多个相同类型的侦听器。

还有更多的想法或建议吗?

4

2 回答 2

4

For any event-based system an asynchronous solution is highly preferred. As you note, it is more lightweight than a blocking solution, which requires a thread per each event receiver. So, Solution B is favored.

One thing to be aware of, though, are threading issues: you will be calling the callbacks in your own thread, so the callback implementor must be prepared to deal with that. The callback code must not assume it is executed on any particular thread; it may as well be executed on a different thread each time.

于 2013-05-20T13:17:12.740 回答
2

观察者模式可能对您有所帮助,尤其是在同一主题可能有多个侦听器的情况下。

定义侦听器哈希图的另一种方法是使用侦听器的 CopyOnWriteArrayList。使用这种方法,添加新侦听器不会干扰侦听器的迭代。

定义一个接受所有可能通知类型的接口的替代方法是定义一个接口,该接口具有一个接受所有可能通知类型的根类或接口的单一方法。例如,此接口可以接收任何事件对象的子类化参数化类型 EVENT。

public interface IObserver<EVENT> {
    public void receive( @NonNull EVENT event );
}
于 2013-05-20T13:18:41.273 回答