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

1 comment:

  1. Objective :

    Observer design pattern in Java is a fundamental core Java pattern, where Observer ( who implements Observer ) watch for any change in state or property of Subject(Who extends Observable). For Example Company(Observable) updates all its shareholders(Observers) for any decision they make. Here Company is Subject and Shareholders are Observers, any change in policy of company and Company notifies all its Shareholders or Observer.

    OR

    There are Stocks in StockExchange market, and there are Stock Observer to always observer the stocks for their prices.

    So here Stock is Observable(extends Observable) and Stock Observer are Observers(implements Observer)

    Customised Example as below -

    package ObservablePatternPackage;

    public interface IStock {

    public void register(IStockObserver o);
    public void unregister(IStockObserver o);
    public void setPrice(String stockName, double stockPrice);
    public void notifyObserver();
    }

    -------------------------------------------------------------------------------------------


    package ObservablePatternPackage;

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Map;

    public class Stock implements IStock, Runnable {

    private ArrayList observers;
    private Map stockPrices = new HashMap();

    public Stock(){
    observers = new ArrayList();
    }

    public void setPrice(String stockName, double stockPrice){
    stockPrices.put(stockName, stockPrice);
    }

    public void register(IStockObserver newObserver) {
    observers.add(newObserver);
    }

    public void unregister(IStockObserver deleteObserver) {

    int observerIndex = observers.indexOf(deleteObserver);
    observers.remove(observerIndex);
    System.out.println(" Observer "+(observerIndex+1)+" deleted ");
    }

    public void notifyObserver() {

    for(IStockObserver observer : observers){
    observer.update(this.stockPrices);
    }
    }

    public void run() {
    notifyObserver();
    }
    }

    -------------------------------------------------------------------------------------------

    package ObservablePatternPackage;

    import java.util.Map;

    public interface IStockObserver {

    public void update(Map stockPrices);
    }


    -------------------------------------------------------------------------------------------

    package ObservablePatternPackage;

    import java.util.Map;

    public class StockObserver implements IStockObserver {

    private static int observerIDTracker = 0;
    private int observerID;

    public StockObserver(){
    this.observerID = ++observerIDTracker;
    System.out.println(" New Observer "+ this.observerID);
    }

    public void update(Map stockPrices) {

    System.out.println("\nObserver "+this.observerID+" --- ");

    for (Map.Entry entry : stockPrices.entrySet()) {
    System.out.println(entry.getKey() + " : Price = " + entry.getValue());
    }

    }

    }

    -------------------------------------------------------------------------------------------

    package ObservablePatternPackage;

    public class NSE_STOCK_EXCHANGE {


    public static void main(String[] args) {

    Stock stock = new Stock();

    stock.setPrice("IBM", 100.10);
    stock.setPrice("APP", 200.10);

    stock.register(new StockObserver());
    stock.register(new StockObserver());
    stock.register(new StockObserver());
    stock.register(new StockObserver());

    Thread stockThread = new Thread(stock);
    stockThread.start();
    }

    }

    -------------------------------------------------------------------------------------------

    OUTPUT --------

    New Observer 1
    New Observer 2
    New Observer 3
    New Observer 4

    Observer 1 ---
    APP : Price = 200.1
    IBM : Price = 100.1

    Observer 2 ---
    APP : Price = 200.1
    IBM : Price = 100.1

    Observer 3 ---
    APP : Price = 200.1
    IBM : Price = 100.1

    Observer 4 ---
    APP : Price = 200.1
    IBM : Price = 100.1



    ReplyDelete