Long Thai
Long Thai

Reputation: 817

Observe the specific type of event

I'm using observer model in Java EE, the idea is to let one service fire events to many observers. However, although all observers are listening to the same event, each of them is only interested a specific event type, which is specified inside an event. My current code is something like this:

public class Service {
    public void fireEvent(EventType type) {
        MyEvent event = new MyEvent(type);
        fire(event);
    }
}

public class TypeAObserver {
    public void observeEvent(@Observes MyEvent event) {
        if (EventType.TYPE_A.equals(event.getType()) {
            // do something
        }
    }
}

public class TypeBObserver {
    public void observeEvent(@Observes MyEvent event) {
        if (EventType.TYPE_B.equals(event.getType()) {
            // do something
        }
    }
}

As you can see, all observers have to check the type before doing further operations, which increases repetition inside the source code. Moreover, as all observers will receive the same event while only few of them actually process it, I'm afraid this will introduce unnecessary performance overhead.

So, I am looking for other approaches, without using any new libraries beside Java EE preferably, to make each observer listen to the specific type of event only.

Upvotes: 0

Views: 939

Answers (1)

Beryllium
Beryllium

Reputation: 12998

  • You could use a separate queue/event for each event type:

public void observeEvent(@Observes MyEventOfType1 event)
public void observeEvent(@Observes MyEventOfType2 event)

  • Build a filtering queue on top of your generic queue: The filtering queue filters on the event type. Then let the consumers observe the filtered queue.

Pseudo code:

public class TypeAFilter {
    List listeners ll = ArrayList<Listener>();

    public void add(Listener l) {
        l.add(ll);
    }

    public void observeEvent(@Observes MyEvent event) {
        if (EventType.TYPE_A.equals(event.getType()) {
            for (Listener l : ll) {
                l.observeEvent(event);
            }
        }
    }
}

}

This basically means that the filter filter is both observer and observable. The filter is observing your service, the consumers of a specific event attach to the filter.

  • Consider using instanceof together with different event classes, but I'm not sure if it's really faster than equals

  • Use qualifiers:

public void observeEvent(@Observes @EventType1 MyEvent event)
public void observeEvent(@Observes @EventType2 MyEvent event)

See Oracle's example, and how qualifiers are defined

Upvotes: 1

Related Questions