1
2
3
4
5
6 import java.util.Vector;
7 import java.util.Iterator;
8 import java.util.Random;
9
10 interface Observer {
11 public abstract void update(NumberGenerator generator);
12 }
13
14 abstract class NumberGenerator {
15 private Vector observers = new Vector();
16 public void addObserver(Observer observer) {
17 observers.add(observer);
18 }
19 public void deleteObserver(Observer observer) {
20 observers.remove(observer);
21 }
22 public void notifyObservers() {
23 Iterator it = observers.iterator();
24 while(it.hasNext()) {
25 Observer o = (Observer)it.next();
26 o.update(this);
27 }
28 }
29 public abstract int getNumber();
30 public abstract void execute();
31 }
32
33 class RandomNumberGenerator extends NumberGenerator {
34 private Random random = new Random();
35 private int number;
36 public int getNumber() {
37 return number;
38 }
39 public void execute() {
40 for(int i=0; i < 20; i++) {
41 number = random.nextInt(50);
42 notifyObservers();
43 }
44 }
45 }
46
47 class DigitObserver implements Observer {
48 public void update(NumberGenerator generator) {
49 System.out.println("DigitObserver:"+generator.getNumber());
50 try {
51 Thread.sleep(100);
52 } catch(InterruptedException e) {
53 }
54 }
55 }
56
57 class GraphObserver implements Observer {
58 public void update(NumberGenerator generator) {
59 System.out.print("GraphObserver:");
60 int count = generator.getNumber();
61 for(int i=0; i < count; i++) {
62 System.out.print('*');
63 }
64 System.out.println("");
65 try {
66 Thread.sleep(100);
67 } catch(InterruptedException e) {
68 }
69 }
70 }
71
72 public class ObserverGenerator {
73 public static void main(String[] args) {
74 NumberGenerator generator = new RandomNumberGenerator();
75 Observer observer1 = new DigitObserver();
76 Observer observer2 = new GraphObserver();
77 generator.addObserver(observer1);
78 generator.addObserver(observer2);
79 generator.execute();
80 }
81 }