Andrei Petrenko
Andrei Petrenko

Reputation: 3950

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. 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.

Upvotes: 1

Views: 1645

Answers (3)

Tomer
Tomer

Reputation: 17930

You can use java.util.concurrent.ConcurrentHashMap for Thread safe hash map.

The structure you need is:

ConcurrentHashMap<EventType,List<Listener>> map;

That way, each listener is registered to several event types.

Upvotes: 4

Devon_C_Miller
Devon_C_Miller

Reputation: 16518

Take a look at EventListenerList. It holds a list of anything implementing EventListener. Then you can call getListeners(class) to get the listeners of type class.

Upvotes: 0

user1329572
user1329572

Reputation: 6406

Perhaps you're looking for the EventListenerList class? But I may have misunderstood you.

Upvotes: 0

Related Questions