Showing posts with label Design Patterns- Observer. Show all posts
Showing posts with label Design Patterns- Observer. Show all posts

Thursday, 3 January 2013

Design Patterns- Observer

Observer Pattern is the fundamental pattern in java. To understand it in simple words, it allows one object(observer) to watch another object(subject). Observer pattern allows the subject and observer to form a publish-subscirbe relationship. Through Observer pattern, observers can register themselves to recieve events from subject. When the subject needs to inform its observer of an event, it simply sends the event to its observers.

For example:
Suppose in a loan application, interest rates are subject to change and depending upon this, several other values changes like EMI or the tenure of the loan :)
so here the subject is interest rate and observer are loan accounts which are register to the subject for the subscription of the changes in interest rates.
When the interest rate changes, it notifies/updates its observers about its changed value and intern each account is modified with its EMI value or Tenure.
diagram from wiki.

So here comes our Intent of the Observer Pattern:

Intent:

Define one to many dependency between objects so that one object change its state, can be notified and updated to other objects automatically. The motivation of doing so is to maintain the consistency of the related objects without making classes tightly coupled.

IN JAVA API:

Java makes our task very easy, in java.util package, we can find interfaces, classes and methods for implementing observer pattern.
Public Interface Observer:
Any class who implements this interface must be notified when subject or observable object change its status.
Update (Observable Ob, Object arg): This method is called when subject is changed.

Class Observable:
It’s a subject to whom observer wants to observe.

Some Important Method:
addObserver(Observer o):add Observers in the set of observers for this subject or observalbel object.

deleteObserver(Observer o): delete Observers in the set of observers .

hasChanged():check if object has changed.

clearChanged():this method will indicate that subject has no changes or all the observers has been notified when changes is made.

notifyObservers(): notify all the observers if object has changed .

http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Observable.html