Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding 'instanceof' in Java

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 class Event and I want to divide them to Session Beans, like

public void divideEvent(Event event) {     if (event instanceof DocumentEvent) {         documentGenerator.gerenateDocument(event);     } else if (event instanceof MailEvent) {         deliveryManager.deliverMail(event);         ...     }     ...  } 

But there could be more than two event types in future, so the if-else will be long and maybe unreadable. Additionally I think instanceof is not really "best practice" in this case.

I could add an abstract method to the Event type and have them divide itself but then I have to inject the specific Session Beans within each entity.

Is there any hint to achieve a "pretty" solution for this problem?

Thanks for any help!

like image 449
fnst Avatar asked May 27 '11 21:05

fnst


1 Answers

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);     } } 
like image 144
Peter Lawrey Avatar answered Sep 22 '22 09:09

Peter Lawrey