Своя реализация EventBus
This commit is contained in:
39
core/src/main/java/mc/core/eventbus/EventBus.java
Normal file
39
core/src/main/java/mc/core/eventbus/EventBus.java
Normal file
@@ -0,0 +1,39 @@
|
||||
package mc.core.eventbus;
|
||||
|
||||
import javafx.util.Pair;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.*;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
@NoArgsConstructor(access = AccessLevel.PRIVATE)
|
||||
public class EventBus {
|
||||
@Getter
|
||||
private static final EventBus insnance = new EventBus();
|
||||
|
||||
private Queue<Event> eventQueue;
|
||||
private Map<Class<? extends Event>, List<Pair<Object, Method>>> subscribes = new HashMap<>();
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public void registerSubscribes(Object subscriberObject) {
|
||||
Stream.of(subscriberObject.getClass().getDeclaredMethods())
|
||||
.filter(method -> method.isAnnotationPresent(Subscriber.class))
|
||||
.filter(method -> method.getReturnType().equals(Void.TYPE))
|
||||
.filter(method -> method.getParameterCount() == 1)
|
||||
.filter(method -> Event.class.isAssignableFrom(method.getParameterTypes()[0]))
|
||||
.forEach(method -> {
|
||||
Class<? extends Event> type = (Class<? extends Event>) method.getParameterTypes()[0];
|
||||
List<Pair<Object, Method>> pairs;
|
||||
if (subscribes.containsKey(type)) {
|
||||
pairs = subscribes.get(type);
|
||||
} else {
|
||||
pairs = new ArrayList<>();
|
||||
subscribes.put(type, pairs);
|
||||
}
|
||||
pairs.add(new Pair<>(subscriberObject, method));
|
||||
});
|
||||
}
|
||||
}
|
||||
11
core/src/main/java/mc/core/eventbus/Subscriber.java
Normal file
11
core/src/main/java/mc/core/eventbus/Subscriber.java
Normal file
@@ -0,0 +1,11 @@
|
||||
package mc.core.eventbus;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Target(value= ElementType.METHOD)
|
||||
@Retention(value= RetentionPolicy.RUNTIME)
|
||||
public @interface Subscriber {
|
||||
}
|
||||
Reference in New Issue
Block a user