java 创建一个简单的事件驱动架构

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13483048/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 12:56:23  来源:igfitidea点击:

Creating a simple event driven architecture

javaeventsarchitectureevent-driven

提问by LiamRyan

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.

目前有一个项目有点麻烦。我正在实现一个游戏,我希望它是事件驱动的。

So far I have an EventHandler class which has an overloaded method depending on what type of event is generated(PlayerMove, Contact, Attack, etc)

到目前为止,我有一个 EventHandler 类,它有一个重载方法,具体取决于生成的事件类型(PlayerMove、Contact、Attack 等)

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?

我将让游戏驱动程序或类生成事件。我的问题是如何在不将事件生成类与事件处理程序紧密耦合的情况下有效地处理事件,并使 EDA 的使用变得多余?

I want to design my own simple handler and not use the built-in Java one for this

我想设计自己的简单处理程序,而不是为此使用内置的 Java 处理程序

回答by ShyJ

If you want to have a single EventHandlerclass with overloaded methods and your event types do not have any subclasses, then this simple code, which uses reflection, should work:

如果你想要一个EventHandler带有重载方法的类,并且你的事件类型没有任何子类,那么这个使用反射的简单代码应该可以工作:

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

However, if you want to have seperate EventHandlers for different events, the following would be better.

但是,如果您想EventHandler为不同的事件设置单独的s,则以下方法会更好。

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