mercredi 31 janvier 2018

Suitable design pattern for event management

We have a modular architecture, in which every module works as an event generator as well as event observer. It is possible that a module can generate multiple events at same time.

We can have two architecture for handling events:

  1. Maintain an observer list for different type of events and call their handlers one by one.

    class Module{
        vector<Module*> event_observer_list[CNT_OF_EVENTS];
        int register(Module* observer, int event_type){
            event_observer_list[event_type].push_back(observer);
        }
        void generate_event(list_of_event_indices){
            for(auto event_index : list_of_event_indices){
                for(auto i : event_observer[event_index])
                    event_observer_list[event_index][i]->handler(some_params);
            }
        }
        int handler(some_params){
            ...
        }
    };
    
    

    In this case we will have to call same observer function handler() multiple times for multiple events. Even if we write separate handlers for each event, we may have to perform some common task (like getting an object from a synchronized map) in each call, which makes this architecture enefficient.

  2. Maintain an observer list common for all events. We will call each module's handler one by one. If a module is not looking for some specific event then it will just skip the processing.

    class Module{
        vector<Module*> event_observer_list;
        int register(Module* observer){
            event_observer_list.push_back(observer);
        }
        void generate_event(list_of_event_types){
            for(i = 0 to event_observer_list.size()){
                event_observer_list[i]->handler(some_params, list_of_event_types);
            }
        }
        int handler(some_params, list_of_event_types){
            ...
        }
    };
    
    

    This architecture is also enefficient because, it is making us to call some unnecessary handlers.

Please provide any possible optimization in the existing architectures or give a totally different design solution.

Aucun commentaire:

Enregistrer un commentaire