-
Notifications
You must be signed in to change notification settings - Fork 0
/
Observer.java
67 lines (52 loc) · 1.42 KB
/
Observer.java
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
public interface Observer{
void update(String latestInfo);
}
public class NewsPapper implements Observer{
void update(String latestInfo){
System.out.println("NewsPapper" + latestInfo);
}
}
public class MailPapper implements Observer{
void update(String latestMail){
System.out.prinln("MailPapper" + latestMail);
}
}
public interface Subject{
void registerObserver(Observer observer);
void removeObserver(Observer observer);
void notifyObserver(Observer observer);
}
public class Loan implements Subject{
private String latestInfo;
private ArrayList<Observer> observers = new ArrayList<Observer>();
public void registerObserver(Observer observer){
this.observers.add(observer);
}
public void removeObserver(Observer observer){
this.observers.remove(observer);
}
public void notifyObserver(){
Iterator iterator = this.observers.iterator();
while(iterator.hasNext()){
Observer observer = (Observer) iterator.next();
observer.update(latestInfo);
}
}
public void setLatestInfo(String info){
this.latestInfo = info;
notifyObserver();
}
@Override
public void notifyObserver(Observer observer) {
// TODO Auto-generated method stub
}
}
public class ObserverTest{
public static void main(String[] args) {
Loan loan = new Loan();
loan.registerObserver(new NewsPapper());
loan.registerObserver(new MailPapper());
loan.setLatestInfo("最新消息1");
loan.setLatestInfo("最新消息2");
}
}