Ju Ju
Ju Ju

Reputation: 199

Why interface is used in observer pattern?

I have read in the book that the application layer is supposed to be independent of the presentation layer. Design pattern are solution to problem like that. Observer pattern is applicable when an object should be able to notify other objects without making assumptions about who those objects are.But a method such as addObserver adds the observers to the list of observers. After that, observerable know which objects are to be notified. And how those list are used? In the book I read, it said that the observerable only access observer through the interface defined in the application layer so that the layer architecture of the system is preserved. Then the interface use that list? lf so, what is the difference?

Upvotes: 0

Views: 1321

Answers (1)

Arthur Noseda
Arthur Noseda

Reputation: 2654

Here, I stripped the not important parts of java.util.Observable a class designed for extension that consumes the Observer interface. This is Java code, but of course any OOP language could implement such pattern.

package java.util;

public class Observable {
    private boolean changed = false;
    private Vector obs;

    public Observable() {
        obs = new Vector();
    }

    public synchronized void addObserver(Observer o) {
        if (o == null)
            throw new NullPointerException();
        if (!obs.contains(o)) {
            obs.addElement(o);
        }
    }

    public void notifyObservers() {
        notifyObservers(null);
    }

    public void notifyObservers(Object arg) {
        Object[] arrLocal;
        synchronized (this) {
            if (!changed)
                return;
            arrLocal = obs.toArray();
            clearChanged();
        }

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

    protected synchronized void setChanged() {
         changed = true;
    }

}

An Observer is added to the Observable through the addObserver method. Observable maintains a list (here a Vector) of Observers. When the Observable changes, setChanged() is called, followed by notifyObservers(). Each Observer has his update() method called to do something with the event. This is for the implementation details.

Now if you look from a design perspective. The Observable only knows of a list of Observers. They could be anything. They could be heterogeneous: user interfaces, job handlers... All they need is to implement Observer and a single method. In Java, this principle is implemented in many specific places like the windowing toolkit Swing, for event handling.

Upvotes: 1

Related Questions