Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observer pattern with two lists of observers

I have a class MyObserver that listens to changes in Notifier. Notifier extends Observable and notify its events with notifyObservers(Object). The object passed as argument is always an instance of the same class. The problem is that each observer need to listen to diferent events. For example one observer needs to listen to state changed events and others to all types of events. How can I do this with observer pattern?

Thanks.

like image 823
David Moreno García Avatar asked Dec 12 '22 11:12

David Moreno García


2 Answers

Use notifyObservers(Object arg) version and create some sort of "event type" object to stick in there. In your observing classes simply filter on the passed in event class.

public void update(Object observable, Object arg) {
    if ( (MyEvent) arg.isEventX() ) { /* do stuff */ }
}
like image 169
Andrew White Avatar answered Dec 28 '22 08:12

Andrew White


I think that the Java built-in implementation of the Observer Pattern is not suitable for your case.

In fact, the general Observer pattern is usable when just one Observable kind of events can arise. In the Observer Design Pattern, all the Observes get notified always.

So, in this case, you need to extend the general Observer pattern, by defining your own Observable interface, for example, this way:

public enum EventKind {
   EVENT_A, EVENT_B, EVENT_C;
}

public interface Observable {
   public void registerObserver(EventKind eventKind);
   public void unregisterObserver(EventKind eventKind);
   public void notifyObservers(EventKind eventKind);
}

Then you can just implement this Observable interface with internal lists for each kind of event to notify. You can still use the Java built-in Observer interface if you wish.

This approach has the following benefits:

  1. You can flexibly add more kind of events without affecting the code of the Observers.
  2. You can register any observer to any event.
  3. You update just the Observers that are effectively interested in each event.
  4. You avoid "empty methods", "event type checking" and other tricks on the Observers side.
like image 37
Mr.Eddart Avatar answered Dec 28 '22 08:12

Mr.Eddart