文章目录
  1. 观察者模式

观察者模式

  • 定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。
    Observer
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
public class Subject {
private List<Observer> observers;
public Subject() {
observers = new ArrayList<>();
}
protected void attach(Observer observer) {
observers.add(observer);
}
protected void detach(Observer observer) {
observers.remove(observer);
}
protected void notify_(Object args) {
observers.forEach(observer -> observer.update(args));
}
}
public class VolumeSubject extends Subject {
private Integer vol;
public void changeVol(Integer vol){
this.vol=vol;
notify_(vol);
}
}
public interface Observer {
void update(Object message);
}
public class SpeakerObserver implements Observer {
public SpeakerObserver(Subject subject){
subject.attach(this);
}
@Override
public void update(Object vol) {
System.out.println("扬声器音量调整"+vol);
}
}
public class VolumeBarObserver implements Observer {
public VolumeBarObserver(Subject subject){
subject.attach(this);
}
@Override
public void update(Object vol) {
System.out.println("音量条显示器调整"+vol);
}
}
public class App {
public static void main(String[] args) {
VolumeSubject subject=new VolumeSubject();
Observer speaker=new SpeakerObserver(subject);
Observer volumeBar=new VolumeBarObserver(subject);
subject.changeVol(4);
subject.changeVol(5);
subject.changeVol(6);
}
}
文章目录
  1. 观察者模式