Watch What is Going On with the Observer Patterns : Observable and Observer « Design Pattern « Java Tutorial






import java.util.Vector;

public class TestObserver {
  public static void main(String args[]) {
    Database database = new Database();
    Archiver archiver = new Archiver();
    Client client = new Client();
    Boss boss = new Boss();

    database.registerObserver(archiver);
    database.registerObserver(client);
    database.registerObserver(boss);
    database.editRecord("delete", "record 1");
  }
}

interface Observer {
  public void update(String operation, String record);
}

interface Subject {
  public void registerObserver(Observer o);

  public void removeObserver(Observer o);

  public void notifyObservers();
}

class Database implements Subject {
  private Vector<Observer> observers;

  private String operation;

  private String record;

  public Database() {
    observers = new Vector<Observer>();
  }

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

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

  public void notifyObservers() {
    for (int loopIndex = 0; loopIndex < observers.size(); loopIndex++) {
      Observer observer = (Observer) observers.get(loopIndex);
      observer.update(operation, record);
    }
  }

  public void editRecord(String operation, String record) {
    this.operation = operation;
    this.record = record;
    notifyObservers();
  }
}

class Client implements Observer {
  public Client() {
  }

  public void update(String operation, String record) {
    System.out.println("The client says a " + operation + " operation was performed on " + record);
  }
}

class Boss implements Observer {
  public Boss() {
  }

  public void update(String operation, String record) {
    System.out.println("The boss says a " + operation + " operation was performed on " + record);
  }
}

class Archiver implements Observer {
  public Archiver() {
  }

  public void update(String operation, String record) {
    System.out
        .println("The archiver says a " + operation + " operation was performed on " + record);
  }
}








34.2.Observable and Observer
34.2.1.Observable and Observer Objects
34.2.2.Demonstrate the Observable class and the Observer interface.
34.2.3.An object may be observed by two or more observers.
34.2.4.Demonstration of 'observer' pattern.
34.2.5.Watch What is Going On with the Observer Patterns
34.2.6.Timeout Observer