* 很常见的例子:猎头和求职者,求职者订阅了猎头职位的信息。有新的职位时,求职者将会收到信息。
*/
public interface Subject {
public void registerObserver(Observer o);
public void removeObserver(Observer o);
public void notifyAllObservers();
}
public interface Observer {
public void update(Subject s);
}
public class HeadHunter implements Subject {
private List<Observer> userList;
private List<String> jobs;
public HeadHunter() {
this.userList = new ArrayList<>();
this.jobs = new ArrayList<>();
}
@Override
public void registerObserver(Observer o) {
userList.add(o);
}
@Override
public void removeObserver(Observer o) {
userList.remove(o);
}
@Override
public void notifyAllObservers() {
for(Observer observer :userList){
observer.update(this);
}
}
public void addJob(String job) {
this.jobs.add(job);
this.notifyAllObservers();
}
public List<String> getJobs(){
return this.jobs;
}
@Override
public String toString(){
return this.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! ");
System.out.println(s);
}
}
class HeadHunter extends Observable{
private List<String> jobs = new ArrayList<>();
public void addJob(String job){
this.jobs.add(job);
this.setChanged();
this.notifyObservers();
}
}
class JobSeeker implements Observer{
@Override
public void update(Observable o, Object arg) {
}
}