Friday, December 7, 2012

Observer Pattern

The observer pattern defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically.
The object which is being watched is called the subject.The objects which are watching the state changes are called observer. Alternatively observer are also called listener.

When To Use
  1. In a mailing list, where every time an event happens (a new product, a gathering, etc.) a message is sent to the people subscribed to the list.
  2. When a change to one object requires changing others, and you don't know how many objects need to be changed.
  3. When an object should be able to notify other objects without making assumptions about who these objects are (avoid tight-coupling). 
 Example Code :

interface Observer {
 public void update(Subject o);
}

interface Subject {
 public void addObserver(Observer o);
 public void removeObserver(Observer o);
 public String getState();
 public void setState(String state);
}


class ObserverImpl implements Observer {
 private String state = "";
 public void update(Subject o) {
   state = o.getState();
   System.out.println("Update received from Subject, state changed to : " + state);
   try{
       Thread.sleep(1000);
       System.err.println("Update received from Subject, state changed to : " + state);
   } catch(Exception ex) {
      ex.printStackTrace();
   }
 }
}
 

import java.util.*;
class SubjectImpl implements Subject {
 private List observers = new ArrayList();

 private String state = "";

 public String getState() {
   return state;
 }

 public void setState(String state) {
   this.state = state;
   notifyObservers();
 }

 public void addObserver(Observer o) {
   observers.add(o);
 }

 public void removeObserver(Observer o) {
   observers.remove(o);
 }

 public void notifyObservers() {
   Iterator i = observers.iterator();
   while (i.hasNext()) {
     Observer o = (Observer) i.next();
     o.update(this);
   }
 }
}

Observer Test Class
public class ObserverTest {
 public static void main(String[] args) {
     for( int i =0 ; i< 10; i++ ) {
       Observer o = new ObserverImpl();
       Subject s = new SubjectImpl();
       s.addObserver(o);
       s.setState("New State"+i);
     }
   }
}

No comments:

Post a Comment