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());
}
}
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
updateand 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.Often, you will just begin the code of your observer by
if (!should_observe(x)) return;whereshould_observetells 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:
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.