dimanche 21 février 2016

Design of Generics based Message Dispatch Framework

I am working on a message dispatch framework where users can register to a particular type of message along with its handler. Used generics as it allowed for easy extension and less code along with ease of usage of the framework , but got stuck at a point. Wondering if i can design it better??

Interface for every event handler

public interface EventProcessor<EventType> {
    void processEvent(EventType eventType);
}

Example event handler

public class TestEvent1Handler implements EventProcessor<Event1>{

    public void processEvent(Event1 eventType) {
        System.out.println("Yay! , got event: "+ eventType.getCode());
    }

}

Event Dispatcher Class

public class EventDispatcher {

    private Map<Class, EventProcessor> eventHandlerMap = new 
        HashMap<Class, EventProcessor>();

    public <EventType> void registerProcessor
        (Class<EventType> eventClass, EventProcessor<EventType> processor){
            System.out.println("for "+ eventClass+ " listener is "+ processor);
            eventHandlerMap.put(eventClass, processor);
            System.out.println("successfully registered");
        }

    public void beginDispatching(){


         for(Class eventClass : eventHandlerMap.keySet()){
             String queueName = getQueueNameFromEventClass(eventClass);

             executorPool.submit(
                     new ConsumerThread(queueName, eventHandlerMap.get(eventClass), eventClass));
         }

    }

    private String getTopicNameFromEventClass(Class eventClass) {
        if(eventClass.equals(Event1.class)){
            return "Event1";
        }
        else if(eventClass.equals(Event2.class)){
            return "Event2";
        }
        else{
            return "default";
        }
    }

Example EventHandler Registration

    dispatcher.registerProcessor(Event1.class,
            new TestEvent1Handler());

This works , but the problem is whoever defines a new message has to come and update the utility method for determining topic name from the event Class - "getTopicNameFromEventClass" in the dispatcher. Any way to avoid this?

Aucun commentaire:

Enregistrer un commentaire