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
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.
2 Answers 2
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.
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);
}
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.