dimanche 25 octobre 2020

What is the best pattern for event notification with different arguments?

I'm looking for an alternative pattern to the following (method 1):

public interface IEventListener {
    void onFoo(String string, Integer integer, ObjectB objectB);
    void onBar(Double d, ObjectA objectA);
}

I'm thinking something like this (method 2):

public interface IEventListener {
    void onEvent(Event event);
}

public enum EVENT_TYPE {
    FOO, BAR
}

public abstract class Event {
    EVENT_TYPE type;
    abstract EVENT_TYPE getType();
}

public class FooEvent extends Event {
    private String string;
    private Integer integer;
    private ObjectB objectB;

    @Override
    EVENT_TYPE getType() {
        return EVENT_TYPE.FOO;
    }
}

public class BarEvent extends Event {
    private Double d;
    private ObjectA objectA;

    @Override
    EVENT_TYPE getType() {
        return EVENT_TYPE.BAR;
    }
}

But I'm not sure how it is easy to use. To handle the event I need to check the event type and cast the event to the correct one, etc.

Maybe there is no alternative to method 1?

Aucun commentaire:

Enregistrer un commentaire