Avoiding 'instanceof' in Java

后端 未结 8 456
灰色年华
灰色年华 2020-12-07 11:14

I have the following (maybe common) problem and it absolutely puzzles me at the moment:

There are a couple of generated event objects which extends the abstract clas

8条回答
  •  失恋的感觉
    2020-12-07 11:37

    You could register each of your handler classes against each event type, and perform dispatch when event happens like this.

    class EventRegister {
    
       private Map> listerMap;
    
    
       public void addListener(Event event, EventListener listener) {
               // ... add it to the map (that is, for that event, get the list and add this listener to it
       }
    
       public void dispatch(Event event) {
               List listeners = map.get(event);
               if (listeners == null || listeners.size() == 0) return;
    
               for (EventListener l : listeners) {
                        l.onEvent(event);  // better to put in a try-catch
               }
       }
    }
    
    interface EventListener {
        void onEvent(Event e);
    }
    

    And then get your specific handlers to implement the interface, and register those handlers with the EventRegister.

提交回复
热议问题