Add singleton EventBus instance

This commit is contained in:
Kai S. K. Engelbart 2020-09-06 15:32:54 +02:00
parent 856e81b090
commit 70bcfd5125
Signed by: kske
GPG Key ID: 8BEB13EC5DF7EF13
2 changed files with 18 additions and 1 deletions

View File

@ -5,7 +5,7 @@
<groupId>dev.kske</groupId> <groupId>dev.kske</groupId>
<artifactId>event-bus</artifactId> <artifactId>event-bus</artifactId>
<version>0.0.1</version> <version>0.0.2</version>
<name>Event Bus</name> <name>Event Bus</name>
<description>An event handling framework for Java utilizing annotations.</description> <description>An event handling framework for Java utilizing annotations.</description>

View File

@ -6,6 +6,9 @@ import java.util.concurrent.ConcurrentHashMap;
/** /**
* Event listeners can be registered at an event bus to be notified when an event is dispatched. * Event listeners can be registered at an event bus to be notified when an event is dispatched.
* <p> * <p>
* A singleton instance of this class can be lazily created and acquired using the
* {@link EventBus#getInstance()} method.
* <p>
* This is a thread-safe implementation. * This is a thread-safe implementation.
* *
* @author Kai S. K. Engelbart * @author Kai S. K. Engelbart
@ -14,6 +17,20 @@ import java.util.concurrent.ConcurrentHashMap;
*/ */
public final class EventBus { public final class EventBus {
private static EventBus singletonInstance;
/**
* Produces a singleton instance of the event bus. It is lazily initialized on the first call.
*
* @return a singleton instance of the event bus.
* @since 0.0.2
*/
public static EventBus getInstance() {
if (singletonInstance == null)
singletonInstance = new EventBus();
return singletonInstance;
}
private final Map<Class<? extends IEvent>, Collection<EventHandler>> bindings private final Map<Class<? extends IEvent>, Collection<EventHandler>> bindings
= new ConcurrentHashMap<>(); = new ConcurrentHashMap<>();
private final Set<EventListener> registeredListeners = ConcurrentHashMap.newKeySet(); private final Set<EventListener> registeredListeners = ConcurrentHashMap.newKeySet();