创建一个简单的事件驱动架构 [英] Creating a simple event driven architecture
问题描述
目前在某个项目上遇到了一些麻烦.我正在实现一个游戏,我希望它是由事件驱动的.
Having a bit of trouble with a project at the moment. I am implementing a game and I'd like to have it event-driven.
到目前为止,我有一个 EventHandler 类,它有一个重载方法,具体取决于生成的事件类型(PlayerMove、Contact、Attack 等)
So far I have an EventHandler class which has an overloaded method depending on what type of event is generated(PlayerMove, Contact, Attack, etc)
我将让游戏驱动程序或类生成事件.我的问题是如何在不将事件生成类与事件处理程序紧密耦合的情况下有效地处理事件,并使 EDA 的使用变得多余?
I will have either the game driver or the class generate the events. My question is how can I efficiently handle the events without tightly coupling the event generating classes to the event handler and making the use of EDA redundant?
我想设计自己的简单处理程序,而不是为此使用内置的 Java 处理程序
I want to design my own simple handler and not use the built-in Java one for this
推荐答案
如果你想要一个带有重载方法的 EventHandler
类,并且你的事件类型没有任何子类,那么这个简单的代码,它使用反射,应该工作:
If you want to have a single EventHandler
class with overloaded methods and your event types do not have any subclasses, then this simple code, which uses reflection, should work:
public class EventHandler {
public void handle (final PlayerMove move) {
//... handle
}
public void handle (final Contact contact) {
//... handle
}
public void handle (final Attack attack) {
//... handle
}
}
public void sendEvent (final EventHandler handler, final Object event) {
final Method method = EventHandler.class.getDeclaredMethod ("handle", new Class[] {event.getClass ()});
method.invoke (handler, event);
}
但是,如果您想为不同的事件设置单独的EventHandler
,那么下面的方法会更好.
However, if you want to have seperate EventHandler
s for different events, the following would be better.
public interface EventHandler<T extends Event> {
void handle (T event);
}
public class PlayerMoveEventHandler implements EventHandler<PlayerMove> {
@Override
public void handle (final PlayerMove event) {
//... handle
}
}
public class EventRouter {
private final Map<Class, EventHandler> eventHandlerMap = new HashMap<Class, EventHandler> ();
public void sendEvent (final Event event) {
eventHandlerMap.get (event.getClass ()).handle (event);
}
public void registerHandler (final Class eventClass, final EventHandler handler) {
eventHandlerMap.put (eventClass, handler);
}
}
这篇关于创建一个简单的事件驱动架构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!