docs/DesignPatterns

annotate code/observer-example.java @ 33:97b57d24fd7b

added sample code; modified summary
author meillo@marmaro.de
date Fri, 10 Aug 2007 22:15:51 +0200
parents
children b2cefbd90180
rev   line source
meillo@33 1 import java.util.Observable;
meillo@33 2 import java.util.Observer;
meillo@33 3
meillo@33 4 public class MessageBoard extends Observable {
meillo@33 5 private String message;
meillo@33 6
meillo@33 7 public String getMessage() {
meillo@33 8 return message;
meillo@33 9 }
meillo@33 10
meillo@33 11 public void changeMessage(String message) {
meillo@33 12 this.message = message;
meillo@33 13 setChanged();
meillo@33 14 notifyObservers(message);
meillo@33 15 }
meillo@33 16
meillo@33 17 public static void main(String[] args) {
meillo@33 18 MessageBoard board = new MessageBoard();
meillo@33 19 Student bob = new Student();
meillo@33 20 Student joe = new Student();
meillo@33 21 board.addObserver(bob);
meillo@33 22 board.addObserver(joe);
meillo@33 23 board.changeMessage("More Homework!");
meillo@33 24 }
meillo@33 25 }
meillo@33 26
meillo@33 27 class Student implements Observer {
meillo@33 28 public void update(Observable o, Object arg) {
meillo@33 29 System.out.println("Message board changed: " + arg);
meillo@33 30 }
meillo@33 31 }