Reputation: 1107
I'll shortly describe how my code structure looks like:
Class Aaa implements EventEmmiter
Class Bbb implements EventEmmiter
Class Aaa Event implements Event:
public class AaaEvent implements Event {
private final Aaa aaa;
public AaaEvent(Aaa aaa) {
this.aaa = aaa;
}
}
Class BbbEvent implements Event:
public class BbbEvent implements Event {
private final Bbb bbb;
public BbbEvent(Bbb bbb) {
this.bbb = bbb;
}
}
I want to create a "createSomething" method to avoid code duplication. I want this method to create, depended of argument type (it can be Aaa or Bbb), a new instance of class which implements from Event.
//EDITED
Below you can find EventPublisher class which works properly but it's not look very nice. I want to avoid if/else or switch implementation cause it could grow more and more with the new classes.
public class EventPublisher {
public void createSomething(EventEmitter eventEmitter) {
DomainEvent event = null;
Class<? extends EventEmitter> eventClass = eventEmitter.getClass();
if (eventClass.isAssignableFrom(Aaa.class)) {
event = new AaaEvents((Aaa) eventEmitter);
} else if (eventClass.isAssignableFrom(Bbb.class)) {
event = new BbbEvents((Bbb) eventEmitter);
} else if () {
some next (eg.CccEvents) class
}
domainEventBus.publish(event);
}
}
For example. If type of EventEmmiter passed as a method argument is Aaa i want to create a new AaaEvent instance.
One more thing. I cannot use inside package of Aaa things from AaaEvent. It works on another direction. I can use things from Aaa package inside AaaEvent.
Can you give me some tips how to implement such things?
Upvotes: 0
Views: 47
Reputation: 20608
You want to implement the factory method pattern:
public interface EventEmmiter {
Event createEvent();
...
}
public class Aaa implements EventEmitter {
@Override public AaaEvent createEvent() { return new AaaEvent(); }
...
}
public class Bbb implements EventEmitter {
@Override public BbbEvent createEvent() { return new BbbEvent(); }
...
}
Now you can simply use it as:
public void createSomething(EventEmitter eventEmitter) {
Event someEvent = eventEmitter.createEvent();
...
}
Upvotes: 3