一、介绍
观察者模式定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态发生变化时,会通知所有观察者对象,使它们能够自动更新自己。
二、代码实现
import java.util.ArrayList; //主题 public class Subject { protected String name; public Subject(String name) { this.name = name; } //同事列表 private ArrayList<Observer> list = new ArrayList<>(); private String action; //增加同事 public void attach(Observer observer) { list.add(observer); } //通知 public void notifyEmployee() { for (Observer item : list) { item.update(); } } //获取通知 public void setAction(String action) { this.action = action; } //设置通知 public String getAction() { return this.action; } } //前台秘书类 public class Secretary extends Subject{ public Secretary(String name) { super(name); } } //boos public class Boss extends Subject{ public Boss(String name) { super(name); } } //观察者 public abstract class Observer { protected String name; protected Subject sub; public Observer(String name, Subject sub) { this.name = name; this.sub = sub; } public abstract void update(); } public class StockObserver extends Observer { public StockObserver(String name, Subject sub) { super(name, sub); } public void update() { System.out.println(this.sub.name + ": " + this.sub.getAction() + this.name + ",股票,请开始工作。"); } } public class NBAObserver extends Observer{ public NBAObserver(String name, Subject sub) { super(name,sub); } public void update() { System.out.println(this.sub.name + ": " + this.sub.getAction() + this.name + ",NBA,请开始工作。"); } } public static void main(String[] args) { Subject secretary1=new Secretary("童子喆"); Observer employee1=new StockObserver("zhangsan",secretary1); Observer employee2=new NBAObserver("lisi",secretary1); secretary1.attach(employee1); secretary1.attach(employee2); secretary1.setAction("老板回来了."); secretary1.notifyEmployee(); }