java:观察者模式
1 前言
观察者模式,又被称为发布-订阅(Publish/Subscribe)模式,他定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态变化时,会通知所有的观察者对象,使他们能够自动更新自己。
2 使用
(2.1)结构
在观察者模式中有如下角色:
Subject:抽象主题(抽象被观察者),抽象主题角色把所有观察者对象保存在一个集合里,每个主题都可以有任意数量的观察者,抽象主题提供一个接口,可以增加和删除观察者对象。
ConcreteSubject:具体主题(具体被观察者),该角色将有关状态存入具体观察者对象,在具体主题的内部状态发生改变时,给所有注册过的观察者发送通知。
Observer:抽象观察者,是观察者的抽象类,它定义了一个更新接口,使得在得到主题更改通知时更新自己。
ConcreteObserver:具体观察者,实现抽象观察者定义的更新接口,以便在得到主题更改通知时更新自身的状态。
(2.2)案例
如公众号使用场景,当多个用户关注了某个公众号时,当公众号有内容更新时,会推送给关注了公众号的多个用户。这里,多个用户就是观察者,公众号就是被观察者。
下面以Java为例来实现一个简单的观察者模式:
Subject接口:
java
/**
* 抽象主题角色类
*/
public interface Subject {
// 添加订阅者(添加观察者对象)
void attach(Observer observer);
// 删除订阅者
void detach(Observer observer);
// 通知订阅者更新消息
void notify(String message, String status);
}
SubscriptionSubject:
java
public class SubscriptionSubject implements Subject{
List<Observer> users = new ArrayList<>();
@Override
public void attach(Observer observer) {
users.add(observer);
}
@Override
public void detach(Observer observer) {
users.remove(observer);
}
@Override
public void notify(String message, String status) {
// 遍历集合
for (Observer user : users) {
// 调用观察者对象中的update方法
user.update(message, status);
}
}
}
Observer:
java
/**
* @author xiaoxu
* @date 2024-04-20 19:43
* learn_java:com.xiaoxu.design.observe.Observer
* 抽象观察者类
*/
public interface Observer {
void update(String message, String status);
}
AbstractObserver:
java
public abstract class AbstractObserver implements Observer{
protected String status;
public AbstractObserver(String status) {
this.status = status;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
ObserveUser:
java
public class ObserveUser extends AbstractObserver{
private String name;
public ObserveUser(String name, String status) {
super(status);
this.name = name;
}
@Override
public void update(String message, String status) {
System.out.println(String.format(
"%s接收到消息:%s.原本状态为:%s," +
"更新后的状态为:%s.",
this.name, message,
this.getStatus(), status));
this.setStatus(status);
}
}
Client(验证上述的效果):
java
public class Client {
public static void main(String[] args) {
// 创建公众号对象
SubscriptionSubject subject = new SubscriptionSubject();
// 创建订阅者,订阅公众号
subject.attach(new ObserveUser("小徐", "online"));
subject.attach(new ObserveUser("小李", "offline"));
// 公众号更新,发出消息给订阅者(观察者对象)
subject.notify("来看心世界", "receive");
}
}
执行结果如下:
java
小徐接收到消息:来看心世界.原本状态为:online,更新后的状态为:receive.
小李接收到消息:来看心世界.原本状态为:offline,更新后的状态为:receive.
(2.3)优缺点
优点:
(1)降低了目标与观察者之间的耦合关系,两者之间是抽象耦合关系。
(2)被观察者发送通知,所有注册的观察者都会收到信息【可以实现广播机制】。
缺点:
(1)如果观察者非常多的话,那么所有的观察者收到被观察者发送的通知会耗时。
(2)如果被观察者有循环依赖的话,那么被观察者发送通知会使观察者循环调用,会导致系统崩溃。
(2.4)使用场景
(1)对象间存在一对多关系,一个对象的状态发生改变会影响其他对象。
(2)当一个抽象模型有两个方面,其中一个方面依赖于另一方面时。
(2.5)JDK中提供的实现
在Java中,通过java.util.Observable类和java.util.Observer接口定义了观察者模式,只要实现它们的子类就可以编写观察者模式实例。
(1)Observable类
Observable类是抽象目标类(被观察者),它有一个Vector集合成员变量,用于保存所有要通知的观察者对象,下面来介绍它最重要的3个方法:
public synchronized void addObserver(Observer o)方法:用于将新的观察者对象添加到集合中。
public void notifyObservers(Object arg)方法:调用集合中的所有观察者对象的update方法,通知它们数据放生改变。通常越晚加入集合的观察者越先得到通知(因为JDK源码是索引从大到小遍历集合中的观察者)。
protected synchronized void setChanged()方法:用来设置一个boolean类型的内部标志,注明目标对象发生了变化。当它为true时,public void notifyObservers(Object arg)才会通知观察者。
JDK的完整Observable类实现如下:
java
package java.util;
public class Observable {
private boolean changed = false;
private Vector<Observer> obs;
/** Construct an Observable with zero Observers. */
public Observable() {
obs = new Vector<>();
}
/**
* Adds an observer to the set of observers for this object, provided
* that it is not the same as some observer already in the set.
* The order in which notifications will be delivered to multiple
* observers is not specified. See the class comment.
*
* @param o an observer to be added.
* @throws NullPointerException if the parameter o is null.
*/
public synchronized void addObserver(Observer o) {
if (o == null)
throw new NullPointerException();
if (!obs.contains(o)) {
obs.addElement(o);
}
}
/**
* Deletes an observer from the set of observers of this object.
* Passing <CODE>null</CODE> to this method will have no effect.
* @param o the observer to be deleted.
*/
public synchronized void deleteObserver(Observer o) {
obs.removeElement(o);
}
/**
* If this object has changed, as indicated by the
* <code>hasChanged</code> method, then notify all of its observers
* and then call the <code>clearChanged</code> method to
* indicate that this object has no longer changed.
* <p>
* Each observer has its <code>update</code> method called with two
* arguments: this observable object and <code>null</code>. In other
* words, this method is equivalent to:
* <blockquote><tt>
* notifyObservers(null)</tt></blockquote>
*
* @see java.util.Observable#clearChanged()
* @see java.util.Observable#hasChanged()
* @see java.util.Observer#update(java.util.Observable, java.lang.Object)
*/
public void notifyObservers() {
notifyObservers(null);
}
/**
* If this object has changed, as indicated by the
* <code>hasChanged</code> method, then notify all of its observers
* and then call the <code>clearChanged</code> method to indicate
* that this object has no longer changed.
* <p>
* Each observer has its <code>update</code> method called with two
* arguments: this observable object and the <code>arg</code> argument.
*
* @param arg any object.
* @see java.util.Observable#clearChanged()
* @see java.util.Observable#hasChanged()
* @see java.util.Observer#update(java.util.Observable, java.lang.Object)
*/
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);
}
/**
* Clears the observer list so that this object no longer has any observers.
*/
public synchronized void deleteObservers() {
obs.removeAllElements();
}
/**
* Marks this <tt>Observable</tt> object as having been changed; the
* <tt>hasChanged</tt> method will now return <tt>true</tt>.
*/
protected synchronized void setChanged() {
changed = true;
}
/**
* Indicates that this object has no longer changed, or that it has
* already notified all of its observers of its most recent change,
* so that the <tt>hasChanged</tt> method will now return <tt>false</tt>.
* This method is called automatically by the
* <code>notifyObservers</code> methods.
*
* @see java.util.Observable#notifyObservers()
* @see java.util.Observable#notifyObservers(java.lang.Object)
*/
protected synchronized void clearChanged() {
changed = false;
}
/**
* Tests if this object has changed.
*
* @return <code>true</code> if and only if the <code>setChanged</code>
* method has been called more recently than the
* <code>clearChanged</code> method on this object;
* <code>false</code> otherwise.
* @see java.util.Observable#clearChanged()
* @see java.util.Observable#setChanged()
*/
public synchronized boolean hasChanged() {
return changed;
}
/**
* Returns the number of observers of this <tt>Observable</tt> object.
*
* @return the number of observers of this object.
*/
public synchronized int countObservers() {
return obs.size();
}
}
(2)Observer接口
Observer接口是抽象观察者,它监视目标对象的变化,当目标对象发生变化时,观察者得到通知,并调用update方法,进行相应的工作。
JDK中Observer接口如下所示:
java
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);
}
举个栗子,警察抓小偷:
警察抓小偷可以使用观察者模式来实现,警察是观察者,小偷是被观察者,代码如下:
小偷是一个被观察者,所以需要继承Observable类:
java
public class Thief extends Observable {
private String name;
public Thief(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void steal() {
System.out.println("小偷" + this.name
+ ": 我偷了隔壁的珍珠奶茶," +
"有没有人来抓我。");
super.setChanged(); // changed = true
super.notifyObservers();
}
}
警察是一个观察者,所以需要让其实现Observer接口:
java
public class Policemen implements Observer {
private String name;
public Policemen(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public void update(Observable o, Object arg) {
System.out.println("小偷传的arg是null" +
"(notifyObservers方法的arg参数):" + arg);
System.out.println("警察" + this.name + ":"
+ ((Thief) o).getName() +
", 站住,你已经被包围了!双脚抱头,倒立站好!");
}
}
Client调用:
java
public class TPClient {
public static void main(String[] args) {
// 创建小偷对象
Thief t = new Thief("采花大盗");
// 创建警察对象
Policemen policemen = new Policemen("小徐");
// 让警察盯着小偷(为小偷添加观察者)
t.addObserver(policemen);
// 小偷偷东西(被观察者发布事件,会被观察者发现)
t.steal();
}
}
执行结果如下:
java
小偷采花大盗: 我偷了隔壁的珍珠奶茶,有没有人来抓我。
小偷传的arg是null(notifyObservers方法的arg参数):null
警察小徐:采花大盗, 站住,你已经被包围了!双脚抱头,倒立站好!