Search code examples
javadesign-patternsobserver-pattern

Is this code abusing the Observer Pattern?


If an Observable object notifies its Observers when one or more of the variables (animals) below is assigned to a new animal, is this an improper use of the Observer Pattern since the Observer will end up setting all four animals when only a subset of them have changed? If so, how could this be fixed? Also, how could an interface be constructed that would specify that the Observer is to set those specific animals and that the Observable is to notify the Observers if those animals are changed? Thanks in advance.


public class ObserverClass implements Observer {
    public void update(Observable o, Object o1) {
        setHippo(o.getHippo());
        setBassetHound(o.getBassetHound);
        setOstrich(o.getOstrich());
        setAntelope((o.getAntelope());
    }
}


Solution

    • Updating only a subset

    Most of the time, it is not a problem, there are few instructions that will just refresh the values. However, if you want to update a subset, you should use the second argument of update and set it to a discriminant that will tell what to update. For this you may use a set of the types of objects that have changed.

    • Observing specific animals

    Often, you will just begin the code of your observer by if (!should_observe(x)) return; where should_observe tells whether the object will be observed.

    The other way of doing it is to create an observable that will be an oberver. A quick example is easier to understand:

    public class OvervableAnimal extends Observable implement Observer {
      private Class<?> animal;
      // constructor omitted
      public synchronized void update(Observable o, Object arg) {
        if (!animal.isInstance(arg))
          return; // not the right animal
        setChanged();
        notifyObservers(arg);
      }
    }
    ObserverClass obs;
    ObserverAnimal obsHippo = new ObservableAnimal(Hippo.class);
    obs.addObserver(obsHippo);
    // use obsHippo if you want to be notified when a hippo has changed
    

    Sometimes it is easier to reimplement entirely the observer pattern: it gives you more control and your observable may be an interface so you won't need to subtype.