Head first design pattern: Observer

The Observer Patterndefines a one-to-many dependency between objects so that when one object changes state, all of its dependents are
notified and updated automatically.

Even though the java have builti-in support for observer pattern, with Observable, and Observer, sometimes we still have to roll our own implementation.

Note: shortcomings of built-in Observable in Java:

violate our OO design principle of programming to interfaces not  implementations. Observable is a class, and we have to subclass it. as we know, a class that already extends another superclass won’t be able to sublcass Observable.

2nd principle violated : favor composition over inheritance. Why?  Observable protects crucial methods: the setChanged() method is protected. This means you can call setChanged()  only if you’ve subclassed Observable. This means you can’t even create an instance of the Observable class and compose it with your own objects, you have to subclass.

Note: Design Principle III:

Strive for loosely coupled designs  between objects that interact.


How to use Java’s Observer Pattern:

For an object to become an observer, as usual, implements the observer interface (this time the java.util.Observer interface) and call addObserver() on any Observable object. Likewise, to remove yourself as an observer just call deleteObserver().

For the Observable to send notification. First of all you need to be Observable by extending the java.util.Observable
superclass. From there it is a two step process: 1. You first must call the setChanged() method to signify that the state has changed in your object.

2 .Then, call one of two notifyObservers() method:   either notifyObservers() , which means  we’re using the PULL model;  or notifyObservers(Object arg), correspondng to PUSH model

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s