Tuesday, April 17, 2012

Observer Pattern


Observer Pattern:-
Here in this pattern, if one object changes it state then all its dependents are notified and updated automatically on each event.
Sample:
MyObservable:
import java.io.File;
import java.util.Observable;
public class MyObservable extends Observable {
      public void findFiles(File file) {
            if (file != null) {
                  if (file.isFile()) {
                        setChanged();
                        notifyObservers(file.getAbsolutePath());
                  } else {
                        File[] fileList = file.listFiles();
                        if (fileList != null) {
                              for (File f : fileList) {
                                    findFiles(f);
                              }
                        }
                  }
            }
      }
}
MyObserver:

import java.util.Observable;
import java.util.Observer; 
public class MyObserver implements Observer {
      public void update(Observable obj, Object arg) {
            System.out.println("\nReceived Response: " + arg);
      }
}
ObserverPattern:
import java.io.File;
public class ObserverPattern {
      public static void main(String[] args) {
        final MyObservable observable = new MyObservable();
        final MyObserver observer = new MyObserver();
       
        observable.addObserver(observer);
        observable.findFiles(new File("."));
      }
}

No comments:

Post a Comment