Koin Arab
Koin Arab

Reputation: 1107

Creating a new instance of implemented class, based on argument class type

I'll shortly describe how my code structure looks like:

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

Answers (1)

Seelenvirtuose
Seelenvirtuose

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

Related Questions