业务总会有环环相扣的联动,一环变化会引发后续环的变动。一个对象的变化,可能会引发一个或多个对象的变化,今天我就要说的能引用此种场景的设计模式——观察者模式。


  • 举例

说实在话,观察者模式只是比较直观的手段——“注册—通知—注销”,响应某个对象变化的手段并不止如此。并且,我对该模式的某个小细节一直存在疑惑,下面会说到。

先给出一个模版。

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
//主题消息实体
class SubjectEntity {
private String code;
private String name;
private String observerName;
public SubjectEntity(String code, String name) {
super();
this.code = code;
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getObserverName() {
return observerName;
}
public void setObserverName(String observerName) {
this.observerName = observerName;
}
@Override
public String toString() {
return "SubjectEntity [code=" + code + ", name=" + name + ", observerName=" + observerName + "]";
}
}
//被观察者
abstract class Subject {
private List<Observer> observers = new ArrayList<Observer>();
public void addObserver(Observer observer) {
observers.add(observer);
}
public void removeObserver(Observer observer) {
observers.remove(observer);
}
public void notifyObserver(SubjectEntity entity) {
for(Observer observer : observers) {
observer.update(entity);
}
}
}
class SimpleSubject extends Subject {
public void action(SubjectEntity entity) {
entity.setName("fuck dick!!!");
notifyObserver(entity);
}
}
//观察者
interface Observer {
public void update(SubjectEntity entity);
}
class SimpleObserver implements Observer {
@Override
public void update(SubjectEntity entity) {
System.out.println(entity);
}
}

我这里把SubjectEntity类作为消息的全部,最后也是把该对象传递到notifyObserver(SubjectEntity entity)方法。

1
2
3
4
5
6
7
8
9
public class ObserverPattern {
public static void main(String[] args) {
SimpleSubject subject = new SimpleSubject();
subject.addObserver(new SimpleObserver());
subject.addObserver(new SimpleObserver());
subject.action(new SubjectEntity("001", "001"));
subject.action(new SubjectEntity("002", "001"));
}
}
  • 我的疑惑

假设我传递消息是被观察者本身的话,又如何?即

1
2
3
interface Observer {
public void update(Subject subject);
}

Subject类的通知方法当然要更改

1
2
3
4
5
public void notifyObserver(Subject subject) {
for(Observer observer : observers) {
observer.update(subject);
}
}

于是乎,当我们实现update(Subject subject)时,就有可能出现这种情况。

1
2
3
4
@Override
public void update(Subject subject) {
subject.notifyObserver(subject);
}

👿👿👿👿👿这让我情何以堪????