本文共 2070 字,大约阅读时间需要 6 分钟。
简单来说,观察者模式=发布者+订阅者。
下面是一个有关猎头的典型的例子。在下面这张图当中有两个角色:猎头和寻找工作的人。找工作的人向猎头订阅,告知自己希望得到一份工作,当有新的工作机会的时候,猎头就会把这个信息通知给曾经向他订阅过的人。
Java代码
Subject接口:1 | public interface Subject { |
2 | public void registerObserver(Observer observer); |
3 | public void removeObserver(Observer observer); |
4 | public void notifyAllObservers(); |
5 | } |
Observer接口:
1 | public interface Observer { |
2 | public void update(Subject subject); |
3 | } |
HeadCounter实现了Subject接口,实际上就是发布者:
01 | public class HeadCounter implements Subject { |
02 |
03 | private List<Observer> observerList; |
04 | private List<String> jobList; |
05 |
06 | public HeadCounter(){ |
07 | observerList = new ArrayList<Observer>(); |
08 | jobList = new ArrayList<String>(); |
09 | } |
10 |
11 | @Override |
12 | public void registerObserver( final Observer observer) { |
13 | if (! observerList.contains(observer)){ |
14 | observerList.add(observer); |
15 | } |
16 | } |
17 |
18 | @Override |
19 | public void removeObserver( final Observer observer) { |
20 | if (observerList.contains(observer)){ |
21 | observerList.remove(observer); |
22 | } |
23 | } |
24 |
25 | @Override |
26 | public void notifyAllObservers() { |
27 | for (Observer observer : observerList){ |
28 | observer.update( this ); |
29 | } |
30 | } |
31 |
32 | public void addJob( final String job){ |
33 | this .jobList.add(job); |
34 | notifyAllObservers(); |
35 | } |
36 |
37 | public List<String> getJobs(){ |
38 | return jobList; |
39 | } |
40 |
41 | public String toString(){ |
42 | return jobList.toString(); |
43 | } |
JobSeeker实现了Observer接口,实际上就是订阅者:
01 | public class JobSeeker implements Observer { |
02 | private String name; |
03 |
04 | public JobSeeker(String name){ |
05 | this .name = name; |
06 | } |
07 |
08 | @Override |
09 | public void update(Subject subject) { |
10 | System.out.println( this .name + " got notified!" ); |
11 | System.out.println(subject); |
12 | } |
13 | } |
程序实例入口:
01 | public class Main { |
02 | public static void main(String[] args) { |
03 | HeadCounter headCounter = new HeadCounter(); |
04 | //注册订阅者 |
05 | headCounter.registerObserver( new JobSeeker( "Mike" )); |
06 | headCounter.registerObserver( new JobSeeker( "Chris" )); |
07 | headCounter.registerObserver( new JobSeeker( "Jeff" )); |
08 | //通知所有订阅者有新的工作机会 |
09 | headCounter.addJob( "Google Job" ); |
10 | headCounter.addJob( "Yahoo Job" ); |
11 | } |
12 | } |