开发者

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 c开发者_运维技巧hanged? 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());
    }
}


  • 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.


you can use notifyObservers(Object) to send information about what state has changed (which will be passed in as the second argument to the update() method). how you encode the changes are up to you. Obviously, you could send a List of the changed animals, but you'd have to do some ugly if blocks to get the animals into the right setters.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜