简体   繁体   English

如何存储多个事件类型的侦听器

[英]How to store Listeners for multiple Event types

I'm trying to implement Observer/Listener pattern with multiple listeners and multiple event types in Java. 我正在尝试使用Java中的多个侦听器和多个事件类型实现Observer / Listener模式。 Each event listener can be interested in one or more event types. 每个事件侦听器都可以对一个或多个事件类型感兴趣。

What is the most efficient way to store listeners for each particular event type and iterate over them (List of Lists, maybe)? 为每个特定事件类型存储侦听器并迭代它们的最有效方法是什么(列表列表,可能)?

Of course, thread-safe solution is strongly preferred. 当然,强烈建议使用线程安全的解决方案。

You can use java.util.concurrent.ConcurrentHashMap for Thread safe hash map. 您可以将java.util.concurrent.ConcurrentHashMap用于线程安全哈希映射。

The structure you need is: 您需要的结构是:

ConcurrentHashMap<EventType,List<Listener>> map;

That way, each listener is registered to several event types. 这样,每个侦听器都注册了几种事件类型。

Perhaps you're looking for the EventListenerList class? 也许您正在寻找EventListenerList类? But I may have misunderstood you. 但我可能误解了你。

Take a look at EventListenerList . 看看EventListenerList It holds a list of anything implementing EventListener . 它包含实现EventListener的任何内容的列表。 Then you can call getListeners(class) to get the listeners of type class . 然后,您可以调用getListeners(class)来获取类型class的侦听器。

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

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