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