Wednesday, November 3, 2010

Observer Design Pattern

Observer Design Pattern: Read about Observer Design patterns from various sources and check the below implementation

package org.paandav.observer;
public interface Observer {
 public void observableStateChanged(Observable obser);
}
package org.paandav.observer;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Observable {
 private List<Observer> observers = null;
 Lock rlock = new ReentrantLock();
 public Observable() {
  observers = new ArrayList<Observer>();
 }
 public void addObserver(Observer observer) {
  try {
   rlock.lock();
   if (observer != null && !observers.contains(observer)) {
    observers.add(observer);
   }
  } finally {
   rlock.unlock();
  }
 }
 public void removeObserver(Observer observer) {
  try {
   rlock.lock();
   if (observer != null && observers.contains(observer)) {
    observers.remove(observer);
   }
  } finally {
   rlock.unlock();
  }
 }
 public void removeAllObservers() {
  try {
   rlock.lock();
   if (observers != null && observers.size() > 0) {
    observers = new ArrayList<Observer>();
   }
  } finally {
   rlock.unlock();
  }
 }
 protected void stateChanged() {
  try {
   rlock.lock();
   if (observers != null && observers.size() > 0) {
    for (Observer ob : observers) {
     ob.observableStateChanged(this);
    }
   }
  } finally {
   rlock.unlock();
  }
 }
}

package org.paandav.observer;
public class IamObservable extends Observable {
 private String data = "INIT";
 public String getData() {
  return data;
 }
 public void setData(String data) {
  this.data = data;
  stateChanged();
 }
}

package org.paandav.observer;
public class IamObserver implements Observer {
 @Override
 public void observableStateChanged(Observable obser) {
  if (obser instanceof IamObservable) {
   IamObservable io = (IamObservable) obser;
   System.out.println("New data in Observer is = " + io.getData());
  }
 }
}

package org.paandav.observer;
public class ObserverTest {
 public static void main(String[] args) {
  IamObservable observale = new IamObservable();
  IamObserver observer = new IamObserver();
  observale.addObserver(observer);
  observale.setData("This is new data");
 }
}

No comments:

Post a Comment