September 30, 2011

Observer Design Pattern code example in Java

The Subject Abstract Type

import Observer;

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

The Observer Abstract Type

import Subject;

public interface Observer {
   public void update(Subject s) { ... }
}

Concrete Implementation of Observer Abstract Type (Subscriber)

import Subject;

public 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);
   }
}

Concrete Implementation of Subject Abstract Type (Publisher)

import Observer;

public 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);
      }
   }
}

The Client

import Subject;
import SubjectImpl;
import Observer;
import ObserverImpl;

public class Client {
   public static void main(String[] args) {
      Observer o = new ObserverImpl();
      Subject s = new SubjectImpl();
      s.addObserver(o);
      s.setState("New State");
   }
}

No comments:

Post a Comment