0

It seems as if this example implementation of the Observer pattern is drawn from the book Headfirst Design Patterns, OReilly, which I am currently reading. Here is a UML diagram from the book

enter image description here

It's not very cleanly visible, but the methods, composing the Subject Interface are:

  • registerObserver()
  • removeObserver()
  • notifyObservers()

What I am skeptical about is the last method. Why would the clients of the interface know about the specific way in which they are called? IMHO the place of this method is inside the concrete subject implementation -ConcreteSubject.

  • BTW: for an interesting take on the Publish/Subscribe Pattern, you can look at Erik Meijer's papers on Rx.NET and IObservable / IObserver where he notices that reactive programming using subscribers is the exact category theoretical dual of interactive programming using iterators, and designs a(n) (pair of) interface(s) that are the exact category theoretical dual of the interface(s) for iterators. That way, oberservers actually seamlessly work with the existing syntax sugar and library algorithms for iterators without any changes. – Jörg W Mittag Jan 12 '16 at 12:47
  • He humorously advised people to "burn their copies of the GoF Design Patterns book because it is crap". That was a joke, of course, what he is referring to is this: as he discovered, there is a very deep mathematical relationship between iterators and observers, and yet, in the diagram about the relationships between the patterns in the book, there is absolutely no link between the two. – Jörg W Mittag Jan 12 '16 at 12:49
  • 1
0

notifyObservers is indeed something internal to the implementation of Subject and should not necessarily be public.

It is helpful for a helper class like ObserverSet. To which you would forward the registerObserver and removeObserver calls and then internally call notifyObservers on.

0

An observable class, which has the add/remove methods:

private List<MyObserver> observers;

public void addObserver(MyObserver o) {
    observers.add(o);
}

public void removeObserver(MyObserver o) {
    observers.remove(o);
}

The notify methods, which don't need to be public. They may be called when anything occurs, also in the observable class.

protected void notifySomething() {
    for (MyObserver o : observers) {
        o.onSomethingHappened();
    }
}

In adition, the observer interface. You can only add objects that implement this interface:

public interface MyObserver {
    public void onSomethingHappened();
}

Finally, i'd have a generic observable interface so that any observable class implements it:

public interface Observable<T> {
    public void addObserver(T o);
    public void removeObserver(T o);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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