简单来说,观察者模式=发布者+订阅者。
下面是一个有关猎头的典型的例子。在下面这张图当中有两个角色:猎头和寻找工作的人。找工作的人向猎头订阅,告知自己希望得到一份工作,当有新的工作机会的时候,猎头就会把这个信息通知给曾经向他订阅过的人。
Java代码
Subject接口:
public interface Subject { public void registerObserver(Observer observer); public void removeObserver(Observer observer); public void notifyAllObservers(); }
Observer接口:
public interface Observer { public void update(Subject subject); }
HeadCounter实现了Subject接口,实际上就是发布者:
public class HeadCounter implements Subject { private List<Observer> observerList; private List<String> jobList; public HeadCounter(){ observerList = new ArrayList<Observer>(); jobList = new ArrayList<String>(); } @Override public void registerObserver(final Observer observer) { if(! observerList.contains(observer)){ observerList.add(observer); } } @Override public void removeObserver(final Observer observer) { if(observerList.contains(observer)){ observerList.remove(observer); } } @Override public void notifyAllObservers() { for(Observer observer : observerList){ observer.update(this); } } public void addJob(final String job){ this.jobList.add(job); notifyAllObservers(); } public List<String> getJobs(){ return jobList; } public String toString(){ return jobList.toString(); }
JobSeeker实现了Observer接口,实际上就是订阅者:
public class JobSeeker implements Observer { private String name; public JobSeeker(String name){ this.name = name; } @Override public void update(Subject subject) { System.out.println(this.name + " got notified!"); System.out.println(subject); } }
程序实例入口:
public class Main { public static void main(String[] args) { HeadCounter headCounter = new HeadCounter(); //注册订阅者 headCounter.registerObserver(new JobSeeker("Mike")); headCounter.registerObserver(new JobSeeker("Chris")); headCounter.registerObserver(new JobSeeker("Jeff")); //通知所有订阅者有新的工作机会 headCounter.addJob("Google Job"); headCounter.addJob("Yahoo Job"); } }
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/140499.html