创建一个简单的事件驱动架构 [英] Creating a simple event driven architecture

查看:121
本文介绍了创建一个简单的事件驱动架构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一点麻烦,此刻的项目。我采取一个游戏,我想它有事件驱动的。

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.

到目前为止,我有其中有一个重载的方法取决于产生什么类型的事件(的PlayerMove,联系方式,攻击等)的事件处理程序类

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

推荐答案

如果您想与重载方法,你的事件类型单一事件处理程序类没有任何子类,那么这个简单的code,它使用反射,应该工作:

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

不过,如果你想拥有单独的事件处理程序 S代表不同的事件,下面的效果会更好。

However, if you want to have seperate EventHandlers 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆