Archived
0

Своя реализация EventBus

This commit is contained in:
2019-01-12 18:58:05 +03:00
parent 169af20f74
commit 3659095851
3 changed files with 112 additions and 0 deletions

View 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));
});
}
}

View 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 {
}