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!
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); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With