Observable and observer : Observer Pattern « Design Pattern « Java






Observable and observer

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

public class MessageBoard extends Observable {
  private String message;

  public String getMessage() {
    return message;
  }

  public void changeMessage(String message) {
    this.message = message;
    setChanged();
    notifyObservers(message);
  }

  public static void main(String[] args) {
    MessageBoard board = new MessageBoard();
    Student bob = new Student();
    Student joe = new Student();
    board.addObserver(bob);
    board.addObserver(joe);
    board.changeMessage("More Homework!");
  }
}

class Student implements Observer {
  public void update(Observable o, Object arg) {
    System.out.println("Message board changed: " + arg);
  }
}

           
         
    
  








Related examples in the same category

1.Observer Pattern - Example in Java
2.Observer Pattern in Java 2
3.A simple demo of Observable and Observer
4.Implementing a Simple Event Notifier
5.Using Observer pattern with two observers observing a changing integer