Monday, December 30, 2013

Observer Design Pattern Example

Observer Design Pattern: Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. -- By THE GOF BOOK

When to use? Observer design pattern is useful when we are interested in the state of an object and want to get notified whenever there is any change in the state of the object. In observer pattern, the object that watch the state of another object is called Observer and the object that is being watched is called Subject.

For example: In GUI programming, event-driven is an important concept. Such as, when you do programming in java UI /swing, you may put a button on the stage, then you’ll add a callback function to the button. The function will be called when there is some action play on the button, such as click. This is almost the same with the observer pattern.

Lets make it clear. Firstly, we care the state of the button; we want know when the button was clicked. Secondly, when the button state was changed, we want to do something, that’s the callback function. Actually, you can consider as the function cares the state of the button. When the button state change, the function will do something. So here the button is observable, and the function maybe the observer.

Keep in mind, An observable object can have one or more observers. An observer may be any object that implements interface Observer. After an observable instance changes, an application calling the Observable's notifyObservers method causes all of its observers to be notified of the change by a call to their update method.