docs/DesignPatterns
diff 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 |
line diff
1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/code/observer-example.java Fri Aug 10 22:15:51 2007 +0200 1.3 @@ -0,0 +1,31 @@ 1.4 + import java.util.Observable; 1.5 + import java.util.Observer; 1.6 + 1.7 + public class MessageBoard extends Observable { 1.8 + private String message; 1.9 + 1.10 + public String getMessage() { 1.11 + return message; 1.12 + } 1.13 + 1.14 + public void changeMessage(String message) { 1.15 + this.message = message; 1.16 + setChanged(); 1.17 + notifyObservers(message); 1.18 + } 1.19 + 1.20 + public static void main(String[] args) { 1.21 + MessageBoard board = new MessageBoard(); 1.22 + Student bob = new Student(); 1.23 + Student joe = new Student(); 1.24 + board.addObserver(bob); 1.25 + board.addObserver(joe); 1.26 + board.changeMessage("More Homework!"); 1.27 + } 1.28 + } 1.29 + 1.30 + class Student implements Observer { 1.31 + public void update(Observable o, Object arg) { 1.32 + System.out.println("Message board changed: " + arg); 1.33 + } 1.34 + }