观察者模式的四种角色:
1、主题接口(Subject):规定了具体主题需要实现的方法
2、观察者接口(Observer):规定了用来更新数据的方法
3、具体主题(ConcreteSubject):实现主题接口
4、具体观察者(ConcreteObserver):实现了观察者接口
主题接口: package DesignPatterns.ObserverMode; public interface Subject { void addObserver(Observer observer); void deleteObserver(Observer observer); void notifyObserver(); } 具体主题: package DesignPatterns.ObserverMode; import javax.print.DocFlavor; import java.util.ArrayList; public class SeekJobCenter implements Subject{ ArrayList<Observer> arrayList; String mess; boolean changed; public SeekJobCenter() { arrayList=new ArrayList<Observer>(); mess=""; changed=false; } @Override public void addObserver(Observer observer) { if (!arrayList.contains(observer)) { arrayList.add(observer); } } @Override public void deleteObserver(Observer observer) { if (arrayList.contains(observer)) { arrayList.remove(observer); } } @Override public void notifyObserver() { if (changed) { for (int i=0;i<arrayList.size();i++) { Observer observer=arrayList.get(i); observer.hearTelephone(mess); } changed=false; } } public void giveNewMess(String newmMess) { if (mess.equals(newmMess)) { changed=false; }else { mess=newmMess; changed=true; } } } 观察者接口: package DesignPatterns.ObserverMode; public interface Observer { void hearTelephone(String mess); } 海归学生观察者: package DesignPatterns.ObserverMode; public class HStudent implements Observer { Subject subject; String messOfQiuZhi; public HStudent(String messOfQiuZhi,Subject subject) { this.subject=subject; subject.addObserver(this); this.messOfQiuZhi=messOfQiuZhi; } @Override public void hearTelephone(String mess) { System.out.println("海归大学生"); System.out.println("我的求职意向:"+messOfQiuZhi); System.out.println("市场通知:"+mess); if (mess.equals(messOfQiuZhi)) { System.out.println("求职意向相符,可以投递"); }else { System.out.println("求职意向不符,不建议投递"); } } } 国内学生观察者: package DesignPatterns.ObserverMode; public class CStudent implements Observer { Subject subject; String messOfQiuZhi; public CStudent(String messOfQiuZhi,Subject subject) { this.subject=subject; subject.addObserver(this); this.messOfQiuZhi=messOfQiuZhi; } public void hearTelephone(String mess) { System.out.println("国内大学生"); System.out.println("我的求职意向:"+messOfQiuZhi); System.out.println("市场通知:"+mess); if (mess.equals(messOfQiuZhi)) { System.out.println("求职意向相符,可以投递"); }else { System.out.println("求职意向不符,不建议投递"); } } } 测试类: package DesignPatterns.ObserverMode; public class Application { public static void main(String[] args) { SeekJobCenter seekJobCenter=new SeekJobCenter(); CStudent cStudent=new CStudent("java程序员",seekJobCenter); HStudent hStudent=new HStudent("产品经理",seekJobCenter); seekJobCenter.giveNewMess("java程序员"); seekJobCenter.notifyObserver(); seekJobCenter.deleteObserver(cStudent); seekJobCenter.giveNewMess("产品经理"); seekJobCenter.notifyObserver(); } }