Using Observer pattern with two observers observing a changing integer : Observer Pattern « Design Pattern « Java






Using Observer pattern with two observers observing a changing integer

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

public class Main {
  public static void main(String[] args) {
    MyObservable observable = new MyObservable();
    MyObserver1 observer1 = new MyObserver1();
    MyObserver2 observer2 = new MyObserver2();
    observable.addObserver(observer1);
    observable.addObserver(observer2);
    observable.start();
    try {
      Thread.sleep(20000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}

class MyObserver1 implements Observer {
  public void update(Observable o, Object arg) {
    Integer count = (Integer) arg;
  }
}

class MyObserver2 implements Observer {
  public void update(Observable o, Object arg) {
    Integer count = (Integer) arg;
  }
}

class MyObservable extends Observable implements Runnable {
  public MyObservable() {
  }

  public void start() {
    new Thread(this).start();
  }

  public void run() {
    int count = 0;
    try {
      Thread.sleep(3000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    count++;
    setChanged();
    notifyObservers(new Integer(count));
  }
}

   
  








Related examples in the same category

1.Observable and observer
2.Observer Pattern - Example in Java
3.Observer Pattern in Java 2
4.A simple demo of Observable and Observer
5.Implementing a Simple Event Notifier