观察者模式又称为发布-订阅模式,涉及的角色有:
● 抽象主题
● 具体主题
● 抽象观察者
● 具体观察者
案例演示:公司发放工资的时候通知所有观察者工资已发放。
/** * 抽象观察者 */ public interface IWatcher { public void getNotice(String str); }
/** * 抽象主题:工资接口 */ public interface ISalary { public void addWatcher(IWatcher watcher); public void removeWatcher(IWatcher watcher); public void notifyAll(String str); }
/** * 具体观察者:员工 */ public class Emp implements IWatcher { @Override public void getNotice(String str) { System.out.println("员工" + str); } }
/** * 具体观察者:经理 */ public class Manager implements IWatcher { @Override public void getNotice(String str) { System.out.println("经理" + str); } }
/** * 具体主题:工资 */ public class Salary implements ISalary { //存放观察者:员工 private List<IWatcher> watcherList = new ArrayList<IWatcher>(); @Override public void addWatcher(IWatcher watcher) { watcherList.add(watcher); } @Override public void removeWatcher(IWatcher watcher) { watcherList.remove(watcher); } @Override public void notifyAll(String str) { for (IWatcher watcher: watcherList) { watcher.getNotice(str); } } }
/** * 测试类 */ public class Test { public static void main(String[] args) { //工资 ISalary salary = new Salary(); //员工 IWatcher emp = new Emp(); //经理 IWatcher manager = new Manager(); //添加观察者 salary.addWatcher(emp); salary.addWatcher(manager); salary.notifyAll("发工资了!"); } }
测试结果如下: