对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。
应用场景:
- 广播监听 (Event / Listener / Status)
推模式(Push)
Observable主动向Observer推送消息,不管对方是否需要。
import java.util.ArrayList;
import java.util.List;
public class Boss {
private String name;
private List<Employee> employees;
public Boss(String name) {
this.name = name;
employees = new ArrayList<>(0);
}
public void employ(Employee employee) {
if (!employees.contains(employee)) {
employees.add(employee);
System.out.println("[Boss] " + name + " employ: " + employee.getName());
}
}
public void fire(Employee employee) {
if (employees.contains(employee)) {
employees.remove(employee);
System.out.println("[Boss] " + name + " fire: " + employee.getName());
}
}
public void assignTask(String task) {
System.out.println("[Boss] " + name + " assign task: " + task);
for (Employee employee : employees) {
//仅把任务内容传给Employee
employee.handleTask(task);
}
}
}
public class Employee {
private String name;
public Employee(String name, Boss boss) {
this.name = name;
boss.employ(this);
}
public void handleTask(String task) {
System.out.println("[Employee] " + name + " handle task: " + task);
}
public String getName() {
return name;
}
}
public class PushObserverTester {
public static void main(String args[]) {
Boss boss = new Boss("Tomas");
Employee bill = new Employee("Bill", boss);
Employee george = new Employee("George", boss);
Employee william = new Employee("William", boss);
boss.assignTask("print document");
Employee donald = new Employee("Donald", boss);
boss.assignTask("make ppt");
boss.fire(george);
boss.assignTask("join meeting");
}
}
拉模式(Pull)
在通知Observer时只传递少量信息,如果观察者需要更具体的信息,再由Observer主动去拉取数据。通常是将Observable自身通过update方法传入到Observer。
public class Boss {
private String name;
private List<Employee> employees;
private String task;
public Boss(String name) {
this.name = name;
employees = new ArrayList<>(0);
}
public void employ(Employee employee) {
if (!employees.contains(employee)) {
employees.add(employee);
System.out.println("[Boss] " + name + " employ: " + employee.getName());
}
}
public void fire(Employee employee) {
if (employees.contains(employee)) {
employees.remove(employee);
System.out.println("[Boss] " + name + " fire: " + employee.getName());
}
}
public void assignTask(String task) {
//记录任务供后期调用
this.task = task;
System.out.println("[Boss] " + name + " assign task: " + task);
for (Employee employee : employees) {
//把Boss引用传给Employee
employee.handleTask(this);
}
this.task = null;
}
public String getTask() {
return task;
}
}
public class Employee {
private String name;
public Employee(String name, Boss boss) {
this.name = name;
boss.employ(this);
}
public void handleTask(Boss boss) {
System.out.println("[Employee] " + name + " handle task: " + boss.getTask());
}
public String getName() {
return name;
}
}
public class PullObserverTester {
public static void main(String args[]) {
Boss boss = new Boss("Tomas");
Employee bill = new Employee("Bill", boss);
Employee george = new Employee("George", boss);
Employee william = new Employee("William", boss);
boss.assignTask("print document");
Employee donald = new Employee("Donald", boss);
boss.assignTask("make ppt");
boss.fire(george);
boss.assignTask("join meeting");
}
}
JDK实现:Observable 和 Observer
推拉模式混合实现,根据 args 是否为 null 可采用不同的模式获取信息:
- 如果 args == null,仅为拉模式
- 否则,推模式和拉模式可任意使用
import java.util.Observable;
public class Boss extends Observable {
private String name;
private String task;
public Boss(String name) {
this.name = name;
}
public void employ(Employee employee) {
addObserver(employee);
System.out.println("[Boss] " + name + " employ: " + employee.getName());
}
public void fire(Employee employee) {
deleteObserver(employee);
System.out.println("[Boss] " + name + " fire: " + employee.getName());
}
public void assignTask(String task) {
this.task = task;
setChanged();
System.out.println("[Boss] " + name + " assign task: " + task);
notifyObservers(task);
clearChanged();
}
public String getTask() {
return task;
}
}
import java.util.Observable;
import java.util.Observer;
public class Employee implements Observer {
private String name;
public Employee(String name, Boss boss) {
this.name = name;
boss.employ(this);
}
public String getName() {
return name;
}
@Override
public void update(Observable o, Object arg) {
System.out.println("(push) [Employee] " + name + " handle task: " + arg);
Boss boss = (Boss) o;
System.out.println("(pull) [Employee] " + name + " handle task: " + boss.getTask());
}
}
public class JdkObserverTester {
public static void main(String args[]) {
Boss boss = new Boss("Tomas");
Employee bill = new Employee("Bill", boss);
Employee george = new Employee("George", boss);
Employee william = new Employee("William", boss);
boss.assignTask("print document");
Employee donald = new Employee("Donald", boss);
boss.assignTask("make ppt");
boss.fire(george);
boss.assignTask("join meeting");
}
}
java.util.Observer
public interface Observer {
void update(Observable o, Object arg);
}
java.util.Observable(核心实现)
public class Observable {
private boolean changed = false;//状态改变标志
private Vector<Observer> obs;//观察者列表
public Observable() {
obs = new Vector<>();
}
//增加观察者
public synchronized void addObserver(Observer o) {
if (o == null)
throw new NullPointerException();
if (!obs.contains(o)) {
obs.addElement(o);
}
}
//移除观察者
public synchronized void deleteObserver(Observer o) {
obs.removeElement(o);
}
//通知观察者(拉模式:Pull)
public void notifyObservers() {
notifyObservers(null);
}
//如果 arg == null,仅为拉模式
//否则,推模式和拉模式可任意使用
public void notifyObservers(Object arg) {
Object[] arrLocal;
synchronized (this) {
if (!changed)
return;
arrLocal = obs.toArray();
clearChanged();
}
//将推送内容和目标对象(Observable)引用都传递给Observer
for (int i = arrLocal.length-1; i>=0; i--)
((Observer)arrLocal[i]).update(this, arg);
}
//标识当前状态为:已变更
protected synchronized void setChanged() {
changed = true;
}
//清除变更状态
protected synchronized void clearChanged() {
changed = false;
}
//判定当前状态标识是否为:已变更
public synchronized boolean hasChanged() {
return changed;
}
}
参考:
https://www.jianshu.com/p/9a8bae159ab2
http://www.runoob.com/design-pattern/observer-pattern.html