使用频率:★★★★★
一、什么是观察者模式
一对多的关系,又叫发布-订阅模式,即一个对象的状态发生变化,所有依赖它的对象能够知道该变化并自动更新;
二、补充说明
一对多:发布者是一,订阅者是多;观察目标是一,观察者是多;状态变化者是一,得到变化通知者是多;
三、角色
抽象主题
具体主题
抽象观察者
具体观察者
四、例子,JAVA实现
发布者为ConcreteSubject对象,PlusObserver和SubObserver为观察者对象,接收到发布者的变化通知后分别做自增和自减操作,并打印结果;
抽象主题
package com.pichen.dp.behavioralpattern.observer; import java.util.ArrayList; import java.util.List; public abstract class Subject { private List<Observer> observers = new ArrayList<Observer>(); public void attach(Observer observer) { observers.add(observer); } public void detach(Observer observer){ observers.remove(observer); } public void notifyAllObservers(double value) { for (Observer observer : observers) { observer.update(value); } } public abstract void change(double value); }
具体主题
package com.pichen.dp.behavioralpattern.observer; public class ConcreteSubject extends Subject{ private double value; /** * @return the value */ public double getValue() { return value; } /** * 〈一句话功能简述〉 * 〈功能详细描述〉 * @see com.pichen.dp.behavioralpattern.observer.Subject#change() */ @Override public void change(double value) { this.value = value; System.out.println("original value:" + value); this.notifyAllObservers(value); } }
抽象观察者
package com.pichen.dp.behavioralpattern.observer; public abstract class Observer { public abstract void update(double value); }
具体观察者
package com.pichen.dp.behavioralpattern.observer; public class PlusObserver extends Observer { public PlusObserver(Subject subject) { subject.attach(this); } @Override public void update(double value) { System.out.println("After plus: "+ (++value)); } }
package com.pichen.dp.behavioralpattern.observer; public class SubObserver extends Observer { public SubObserver(Subject subject) { subject.attach(this); } @Override public void update(double value) { System.out.println("After sub: "+ (--value)); } }
调用示例
package com.pichen.dp.behavioralpattern.observer; public class Main { public static void main(String[] args) { Subject subject = new ConcreteSubject(); new SubObserver(subject); new PlusObserver(subject); subject.change(3.0); subject.change(10.2); } }
结果打印
original value:3.0 After sub: 2.0 After plus: 4.0 original value:10.2 After sub: 9.2 After plus: 11.2