曹耘豪的博客

观察者模式

又叫发布-订阅模式(Publish-Subscribe Pattern),获取变更消息的方式从主动变为被动

例如,我们(Person)订阅一个新闻网站(NewsWebsite),每当有新的新闻(News)时,通知我们

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
interface Observer { void update(String news); }
interface Observable { void addObserver(Observer observer); }

class NewsWebsite implements Observable {
List<Observer> observers = new ArrayList();

public void addObserver(Observer observer) {
observers.add(subscriber)
}

public void publish(String news) {
for (Observer observer: observers) {
observer.update(news)
}
}
}

class Person implements Observer {
public void update(String news) {
System.out.println('Getted news !')
}
}

NewsWebsite newsWebsite = new NewsWebsite();
Observer a = new Person();
newsWebsite.addObserver(a);

newsWebsite.publish('news!')
   /