Observable and Observer Objects : Observable and Observer « Design Pattern « Java Tutorial






import java.util.Observable;
import java.util.Observer;

class MyObservable extends Observable {
  public void drinkPotion() {
    name = "java2s ";
    setChanged();
    notifyObservers();
  }
  public String getName() {
    return name;
  }
  private String name = "java2s";
}
class Person implements Observer {
  public Person(String name, String says) {
    this.name = name;
    this.says = says;
  }
  public void update(Observable thing, Object o) {
    System.out.println("It's " + ((MyObservable) thing).getName() + "\n" + name + ": " + says);
  }
  private String name;
  private String says;
}
public class MainClass {
  public static void main(String[] args) {
    MyObservable man = new MyObservable();
    Observer[] crowd = { 
        new Person("A", "a"),
        new Person("B", "b"),
        new Person("C", "c"),
        new Person("D", "d"),
        new Person("E", "e") };
    for (Observer observer : crowd) {
      man.addObserver(observer);
    }
    man.drinkPotion();
  }
}
It's java2s 
E: e
It's java2s 
D: d
It's java2s 
C: c
It's java2s 
B: b
It's java2s 
A: a">








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