27

I've recently read about Java's Observable class. What I don't understand is this: before notifying the observers (notifyObservers()) I must call setChanged(). There is a boolean inside notifyObservers method that requires us to call setChanged. What is the purpose of the boolean value and why must I call setChanged()?

1
  • 1
    It's worth noting that this feature does not often appear in other renditions of this pattern, for instance JavaBeans events/listeners. Observer/Observable is an awful pair of class/interface. The point of patterns is that repeat, rather than referring to specific classes. Feb 27, 2013 at 20:00

5 Answers 5

29

In a long treatment you may call several times setChanged() but at end, only once notifyObservers(). If, before end, for internal reason you decide to rollback you may choose to call clearChanged(). In the later case, notifyObservers() has no effect.

4

setChanged()

Marks this Observable object as having been changed; the hasChanged method will now return true.

notifyObservers()

If this object has changed, as indicated by the hasChanged method, then notify all of its observers and then call the clearChanged method to indicate that this object has no longer changed.

Basically you use setChanged() to notify the observer superclass that a change has occurred. Then you call the notifyObservers() method to fire off to tell observers what is changed.

The setChanged() there because it allows for a class to undo changes before notify observers by calling clearChanged(). If you didn't setChanged() flag then you are essentially notifying observers and there are no changes detected so they will not respond to the "notify".

see my code for more explanation:

The Main Method public class SpeedRunner {

public static void main(String[] args) {
    SpeedMonitor monitor = new SpeedMonitor();
    // Create a speedometer and register the monitor to it...
    SpedoMeter speedo = new SpedoMeter();
    speedo.addObserver(monitor);
    // Drive at different speeds...
    speedo.setCurrentSpeed(50);
    speedo.setCurrentSpeed(70);
    speedo.setCurrentSpeed(40);
    speedo.setCurrentSpeed(100);
    speedo.setCurrentSpeed(69);
}

The Observer (object that is informed when something interesting happens):

//this is the observer since it is observing changes in the speedo.
public class SpeedMonitor implements Observer {
public static final int SPEED_TO_ALERT = 70;

public void update(Observable obs, Object obj) {
    SpedoMeter speedo = (SpedoMeter) obs;
    if (speedo.getCurrentSpeed() > SPEED_TO_ALERT) {
        System.out.println("** ALERT ** Driving too fast! (" + speedo.getCurrentSpeed() + ")");
    } else {
        System.out.println("... nice and steady ... (" + 
        speedo.getCurrentSpeed() + ")");
        }
    }
}

The subject (the the object of interest)

public class SpedoMeter extends Observable{
private int currentSpeed;

public SpedoMeter(){
    currentSpeed = 0;
}

public void setCurrentSpeed(int speed){
    currentSpeed = speed;

//        setChanged();
    notifyObservers();
}

        public int getCurrentSpeed() {
        return currentSpeed;
    }

}

comment out the setChanged() and you will notice nothing is picked up by the observer hence the console is empty.

See this textbook. Its really good to learn design patterns.

Bevis, Tony. Java Design Pattern Essentials (Kindle Location 1835). Ability First Limited. Kindle Edition.

1

the setchanged() is used as indication or flag for changing the state. if it true the notifyObservers() can run and update all the observers.if it false the notifyObservers() is called without calling the setchanged() and the observers will not be notified.

1

the may reason may be setChanged() is has a protected modifier. Meanwhile, notifyObservers() could be invoked anywhere, even by a observer. Since that, observable and observer may interact with each other with this mechanism.

0
public void notifyObservers(Object arg) {
    /*
     * a temporary array buffer, used as a snapshot of the state of
     * current Observers.
     */
    Observer[] arrLocal;

    synchronized (this) {
        /* We don't want the Observer doing callbacks into
         * arbitrary Observables while holding its own Monitor.
         * The code where we extract each Observable from
         * the ArrayList and store the state of the Observer
         * needs synchronization, but notifying observers
         * does not (should not).  The worst result of any
         * potential race-condition here is that:
         *
         * 1) a newly-added Observer will miss a
         *   notification in progress
         * 2) a recently unregistered Observer will be
         *   wrongly notified when it doesn't care
         */
        if (!hasChanged())
            return;

        arrLocal = observers.toArray(new Observer[observers.size()]);
        clearChanged();
    }

    for (int i = arrLocal.length-1; i>=0; i--)
        arrLocal[i].update(this, arg);
}

The comment is the reason

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.