设计模式---观察者模式
一、观察者模式(Observer)
定义了一种一对多的依赖关系,当一个对象的状态发生变化时,会通知所有观察者对象,使它们能够自动更新自己。
二、四个角色
抽象通知者:Subject(抽象类或接口)
具体通知者:ConcreteSubject类,里面定义一个集合(如List),保存所有的观察者对象
抽象观察者:Observer(抽象类或接口)
具体观察者:ConcreteObserver类
三、程序示例
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//抽象通知者: //5个接口方法:增加观察者、移除观察者、设置状态、获取状态、通知 public interface Subject { void attach(Observer observer);//增加 void detach(Observer observer);//移除 void setState(String state);//设置状态 String getState(); //获取状态 void notifyObservers(); //通知 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//具体通知者: class ConcreteSubject implements Subject { // 存储观察者的链表 private List<Observer> observersList = new LinkedList<Observer>(); //存储状态 private String state = null; public void attach(Observer observer) { observersList.add(observer); } public void detach(Observer observer) { observersList.remove(observer); } public void setState(String state) { this.state = state; } public String getState() { return state; } public void notifyObservers() { for (Observer observer : observersList) { observer.update(this); } } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//抽象观察者 interface Observer { void update(Subject subject); }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//具体观察者 class StuObserver implements Observer { private String name; public StuObserver(String name) { this.name = name; } public void update(Subject subject) { if (subject.getState().equals("老师来了")) { System.out.println(name+" 同学, 开始学习!"); } else if (subject.getState().equals("打球去")) { System.out.println(name+" ,打球去喽!"); } } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class TestMain { public static void main(String [] args) { //被观察者:通知者 Subject subject = new ConcreteSubject(); String state = "老师来了"; //打球去 老师来了 //观察者 Observer obs1 = new StuObserver("sina"); Observer obs2 = new StuObserver("qq"); Observer obs3 = new StuObserver("google"); subject.attach(obs1); subject.attach(obs2); subject.attach(obs3); subject.setState(state); subject.detach(obs2); subject.notifyObservers(); } }