Java设计模式:观察者模式
23 Sep 2014注:本文为译文,原文出处java-design-patterns-in-stories
简而言之, 观者模式 = 发布者 + 订阅者.
观察着模式一直被用于图形用户界面的行为监听器中. Swing GUI的例子展示了行为监听器是如何像观察者一样工作的.
下面是一个典型的关于猎头的离职. 在图中有2个角色 - 猎头与应聘者. 应聘者订阅了猎头的信息, 当有新的工作机会时, 猎头会通知应聘者.
类图
Java代码
主题接口.
public interface Subject {
public void registerObserver(Observer o);
public void removeObserver(Observer o);
public void notifyAllObservers();
}
观察者接口.
public interface Observer {
public void update(Subject s);
}
猎头类实现主题接口
import java.util.ArrayList;
public class HeadHunter implements Subject{
//define a list of users, such as Mike, Bill, etc.
private ArrayList<Observer> userList;
private ArrayList<String> jobs;
public HeadHunter(){
userList = new ArrayList<Observer>();
jobs = new ArrayList<String>();
}
@Override
public void registerObserver(Observer o) {
userList.add(o);
}
@Override
public void removeObserver(Observer o) {}
@Override
public void notifyAllObservers() {
for(Observer o: userList){
o.update(this);
}
}
public void addJob(String job) {
this.jobs.add(job);
notifyAllObservers();
}
public ArrayList<String> getJobs() {
return jobs;
}
public String toString(){
return jobs.toString();
}
}
应聘者是一个观察者.
public class JobSeeker implements Observer {
private String name;
public JobSeeker(String name){
this.name = name;
}
@Override
public void update(Subject s) {
System.out.println(this.name + " got notified!");
//print job list
System.out.println(s);
}
}
开始.
public class Main {
public static void main(String[] args) {
HeadHunter hh = new HeadHunter();
hh.registerObserver(new JobSeeker("Mike"));
hh.registerObserver(new JobSeeker("Chris"));
hh.registerObserver(new JobSeeker("Jeff"));
//Each time, a new job is added, all registered job seekers will get noticed.
hh.addJob("Google Job");
hh.addJob("Yahoo Job");
}
}
JDK中的观察者模式
java.util.EventListener
comments powered by Disqus