Java设计模式 —— 观察者模式

2023-05-19,,

16 观察者模式

16.1 观察者模式概述

Observer Pattern: 定义对象之间的依赖关系(一对多),当一个对象的状态发生改变时,其关联的依赖对象均收到通知并自动更新。

观察者模式又称:发布-订阅模式源-监听器模式

观察者模式结构图如下所示:

16.2 观察者模式实现

16.2.1 抽象目标类

被观察的对象,其中定义了一个 观察者 集合,提供一系列方法来增加和删除观察者对象,同时其定义了通知方法来通知观察者目标对象状态的变化。

public abstract class Subject {
protected List<Observer> observers = new ArrayList<>(); public void add(Observer observer) {
observers.add(observer);
} public void remove(Observer observer) {
observers.remove(observer);
} public abstract void notify();
}

16.2.2 具体目标类

该类实现抽象目标类的 notify 方法,同时它还实现了目标类中定义的抽象业务方法。

public class ConcreteSubject extends Subject {
private String state; public void notify() {
if (this.state.equals("changed")) {
for (Object observer : observers) {
observer.update();
}
}
}
}

16.2.3 观察者接口

观察者一般定义为接口,声明数据更新的方法。

public interface Observer {
public void update();
}

16.2.4 具体观察者

具体观察者update方法可以包含一个指向具体观察目标对象的引用

public class ConcreteObserver implements Observer {
private String state; public ConcreteObserver(String state) {
this.state = state;
} public void update() {
// 执行具体更新逻辑
}
}

16.2.5 客户端调用

public class Client {
public static void main(String[] args) {
Subject subject = new ConcreteSubject();
Observer observer1 = new ConcreteObserver("1");
Observer observer2 = new ConcreteObserver("2"); subject.add(observer1);
subject.add(observer2); // 某些状态发生变化,导致notify()方法被调用,通知所有观察者完成更新
subject.notify();
}
}

16.3 JDK中的观察者模式支持

16.3.1 java.util.Observer

该接口充当抽象观察者类,提供抽象的 update() 方法

package java.util;

/**
* A class can implement the <code>Observer</code> interface when it
* wants to be informed of changes in observable objects.
*
* @author Chris Warth
* @see java.util.Observable
* @since JDK1.0
*/
public interface Observer {
/**
* This method is called whenever the observed object is changed. An
* application calls an <tt>Observable</tt> object's
* <code>notifyObservers</code> method to have all the object's
* observers notified of the change.
*
* @param o the observable object.
* @param arg an argument passed to the <code>notifyObservers</code>
* method.
*/
void update(Observable o, Object arg);
}

16.3.2 java.util.Observable

该类充当抽象观察目标类(通过继承该类,扩展添加自己的业务方法),使用 Vector 存储观察对象列表,变量changed 存储观察目标是否发生改变

package java.util;

public class Observable {
// 存储变化状态
private boolean changed = false;
// 存储观察者列表,线程安全的List
private Vector<Observer> obs; /** Construct an Observable with zero Observers. */
public Observable() {
obs = new Vector<>();
} // 线程安全,添加 observer 到 obs
public synchronized void addObserver(Observer o) {
if (o == null)
throw new NullPointerException();
if (!obs.contains(o)) {
obs.addElement(o);
}
} // 删除列表中的 observer
public synchronized void deleteObserver(Observer o) {
obs.removeElement(o);
} // 通知方法
public void notifyObservers() {
notifyObservers(null);
} public void notifyObservers(Object arg) {
/*
* a temporary array buffer, used as a snapshot of the state of
* current Observers.
*/
Object[] arrLocal; synchronized (this) {
/* We don't want the Observer doing callbacks into
* arbitrary code while holding its own Monitor.
* The code where we extract each Observable from
* the Vector and store the state of the Observer
* needs synchronization, but notifying observers
* does not (should not). The worst result of any
* potential race-condition here is that:
* 1) a newly-added Observer will miss a
* notification in progress
* 2) a recently unregistered Observer will be
* wrongly notified when it doesn't care
*/
if (!changed)
return;
arrLocal = obs.toArray();
clearChanged();
} for (int i = arrLocal.length-1; i>=0; i--)
((Observer)arrLocal[i]).update(this, arg);
} // 删除所有观察者
public synchronized void deleteObservers() {
obs.removeAllElements();
} protected synchronized void setChanged() {
changed = true;
} protected synchronized void clearChanged() {
changed = false;
} public synchronized boolean hasChanged() {
return changed;
} public synchronized int countObservers() {
return obs.size();
}
}

16.4 观察者模式与MVC

MVC架构模式角色分类

Model: 模型
View: 视图
Controller: 控制器

Model 充当观察目标,View 充当观察者,Controller 充当外部作用改变Model的状态,View则会观察到Model的改变,并更新自己的显示内容。

16.5 观察者模式优/缺点

观察者模式使用频率非常高,为实现对象之间的联动提供了一套完整的解决方案,如发布与订阅场景、监听器Listener等。

观察者模式优点

观察目标只需维护一个抽象观察者集合,无需了解具体观察者的实现,降低耦合性
观察者模式支持广播通信,可以向所有已注册的观察者发送通知,简化一对多系统设计

观察者模式缺点

注册观察者时需要获取到观察目标对象才能完成注册
如果一个观察目标有非常多观察者,轮询通知所有观察者开销会较大


参考文章

    设计模式-刘伟

Java设计模式 —— 观察者模式的相关教程结束。

《Java设计模式 —— 观察者模式.doc》

下载本文的Word格式文档,以方便收藏与打印。