forked from john-bai/DesignPatterns
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathObserver.java
More file actions
96 lines (76 loc) · 1.67 KB
/
Copy pathObserver.java
File metadata and controls
96 lines (76 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package designpatterns;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author jtherrell
*/
/*
*/
class Subject {
private List<Observer> observers;
private Log log;
private String title;
public Subject(String title, Log log) {
observers = new ArrayList<Observer>();
this.title = title;
this.log = log;
}
public void notifyObservers() {
for (Observer observer : observers) {
log.append("notifying " + observer.getClass().getSimpleName() + "\n");
observer.update();
}
}
public void attach(Observer observer) {
if (observer != null)
observers.add(observer);
}
public void detach(Observer observer) {
observers.remove(observer);
}
public Log log() {
return log;
}
public String title() {
return title;
}
public void setTitle(String title) {
this.title = title;
notifyObservers();
}
}
interface Observer {
public void update();
}
class ObserverA implements Observer {
private Subject subject;
public ObserverA(Subject subject) {
this.subject = subject;
}
public void update() {
subject.log().append(this.getClass().getSimpleName() + " notified!\n");
}
}
class ObserverB implements Observer {
private Subject subject;
public ObserverB(Subject subject) {
this.subject = subject;
}
public void update() {
subject.log().append(this.getClass().getSimpleName() + " notified!\n");
}
}
class ObserverC implements Observer {
private Subject subject;
public ObserverC(Subject subject) {
this.subject = subject;
}
public void update() {
subject.log().append(this.getClass().getSimpleName() + " notified!\n");
}
}