Avoiding 'instanceof' in Java

后端 未结 8 457
灰色年华
灰色年华 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:45

    The simplest approach is to have the Event provide a method you can call so the Event knows what to do.

    interface Event {
        public void onEvent(Context context);
    }
    
    class DocumentEvent implements Event {
        public void onEvent(Context context) {
             context.getDocumentGenerator().gerenateDocument(this);
        }
    }
    
    class MailEvent implements Event {
        public void onEvent(Context context) {
             context.getDeliveryManager().deliverMail(event);
        }
    }
    
    
    class Context {
        public void divideEvent(Event event) {
            event.onEvent(this);
        }
    }
    

提交回复
热议问题