对于观察者,很多开发者并不陌生,在日常开发过程中,这也是一个非常常见的设计模式,尤其是Android小伙伴,很多人都知道broadcast就是一个典型的观察者模式,还有最近很火的rxjava,响应式编程中,观察者模式扮演着一个很重要的角色,但观察者模式具体是怎么样运转的,部分小伙伴就有点模糊了。
先从日常生活中一个例子开始说起,在看电视的过程中,我们经常看到一些抗日神剧中有这么一个剧情,鬼子进村,在进村的过程中,总会有一些一些人通风报信,然后通知村里的人能躲的躲,能藏的藏,能跑的跑,或者中路再搞个埋伏,抓到了以后是手撕还是其它方式处理,在此就先不做讨论。。。其实这个过程中就是一个典型的观察者模式,下面,我们先看一下手撕鬼子的UML。
DevilsSubject.java
/**
*
* created by zm on 2016-5-28
* 继承Observable,此类等同于上述UML的Devil(小鬼子),其它对号入座
* 观察鬼子是否来袭击
*
*/
public class DevilsSubject extends Observable
{
private String assault;
public String isAssault() {
return assault;
}
public void setAssault(String assault) {
this.assault = assault;
//可通过this.hasChanged()获取是否发生改变,这里我们统一设置成改变,以便测试
this.setChanged();
this.notifyObservers(assault);
}
}
VillagerObserver.java
/**
*
* created by zm on 2016-5-28
*
* VillagerObserver(放哨的村民),观察小鬼子行动
*
*/
public class VillagerObserver implements Observer
{
public void update(Observable o, Object obj) {
// TODO Auto-generated method stub
String assault = (String) obj;
System.out.println(assault);
}
}
Client.java
public class Client
{
public static void main(String[] args) {
VillagerObserver yes = new VillagerObserver();
VillagerObserver no = new VillagerObserver();
DevilsSubject devilsSubject = new DevilsSubject();
//如果观察者与集合中已有的观察者不同,则向对象的观察者集中添加此观察者。
devilsSubject.addObserver(yes);
devilsSubject.addObserver(no);
devilsSubject.setAssault("前方有一坨鬼子来了");
devilsSubject.setAssault("鬼子见阎王了,在来村的路上就被村民手撕了");
//返回 Observable 对象的观察者数目
System.out.println(devilsSubject.countObservers());
System.out.println("................");
devilsSubject.deleteObserver(yes);
devilsSubject.setAssault("鬼子来了");
System.out.println(devilsSubject.countObservers());
}
}
运行的结果:
前方有一坨鬼子来了
前方有一坨鬼子来了
鬼子见阎王了,在来村的路上就被村民手撕了
鬼子见阎王了,在来村的路上就被村民手撕了
Observable对象的观察者数目:2个
................
鬼子来了
Observable对象的观察者数目:1个
下面是observable源码
package java.util;
/**
* This class represents an observable object, or "data"
* in the model-view paradigm. It can be subclassed to represent an
* object that the application wants to have observed.
* <p>
* An observable object can have one or more observers. An observer
* may be any object that implements interface <tt>Observer</tt>. After an
* observable instance changes, an application calling the
* <code>Observable</code>‘s <code>notifyObservers</code> method
* causes all of its observers to be notified of the change by a call
* to their <code>update</code> method.
* <p>
* The order in which notifications will be delivered is unspecified.
* The default implementation provided in the Observable class will
* notify Observers in the order in which they registered interest, but
* subclasses may change this order, use no guaranteed order, deliver
* notifications on separate threads, or may guarantee that their
* subclass follows this order, as they choose.
* <p>
* Note that this notification mechanism has nothing to do with threads
* and is completely separate from the <tt>wait</tt> and <tt>notify</tt>
* mechanism of class <tt>Object</tt>.
* <p>
* When an observable object is newly created, its set of observers is
* empty. Two observers are considered the same if and only if the
* <tt>equals</tt> method returns true for them.
*
* @author Chris Warth
* @see java.util.Observable#notifyObservers()
* @see java.util.Observable#notifyObservers(java.lang.Object)
* @see java.util.Observer
* @see java.util.Observer#update(java.util.Observable, java.lang.Object)
* @since JDK1.0
*/
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();
}
}
再附上Observable的api
根据源码中最上部分的注释,翻译成中文后,大体的意思是此类是一个被观察者。它可以派生子类来表示一个应用程序想要观察的对象。一个可观察到的对象(observable)可以有一个或多个观察者(observer)。一个观察者可以是任何实现接口的观察者的对象。修改后可观察到的实例,应用程序调用notifyObservers方法使所有的观察者调用更新方法。通知的顺序将是未指定的。请注意,这与线程通知机制无关,完全独立于类对象的等待和通知机制。当一个可观察的对象是新创建的,它的观察是空的。当且仅当这个方法返回true,两个观察者是同步的。
源码中,起关键性作用的就是vector和changed,在observable实例化的时候,就初始化了一个空的vector,可以通过vector添加和移除vector操作后,当observable发生改变时,通过changed去判断是否通知,在我们的上述示例代码中使用setChanged(),主要是因为第一次加入的时候,不会去调用observer的update方法,也就是changed为false,当changed为false时,直接从notifyObservers方法中return,只有changed为true的时候才通知刷新,刷新之前,重新把changed赋值为false,提取上述源码中的关键代码如下:
public void notifyObservers(Object arg) {
Object[] arrLocal;
synchronized (this) {
if (!changed)
return;
arrLocal = obs.toArray();
clearChanged();
}
for (int i = arrLocal.length-1; i>=0; i--)
((Observer)arrLocal[i]).update(this, arg);
}
observer类
/**
* 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);
}
observer就是一个接口,里面一个update方法,这个类没太多需要解释的,有点Java基础的都可以明白。
现在一目了然了,Observer模式是一种行为模式,它的作用是当一个对象的状态发生改变的时候,能够自动通知其他关联对象,自动刷新对象状态。Observer模式提供给关联对象一种同步通信的手段,使其某个对象与依赖它的其他对象之间保持状态同步。
抽象主题角色(Subject)内部其实就是一个Vector,在addObserver的时候,就把需要的观察者添加到Vector中。在deleteObserver的时候,就把传进来的观察者从容器中移除掉。主题角色又叫抽象被观察者角色(observable),一般用一个抽象类或者接口来实现。
observable与observer是一种一对多的依赖关系,可以让多个观察者对象同时监听某一个主题对象。观察者模式有时被称作发布/订阅模式(Publish/Subscribe),对于这名称很贴切的,就好比我们订阅了报纸,每次报社新报纸出版发售的时候,就会根据订阅的客户一一发报纸,通知客户阅读。
ConcreteSubject:具体主题角色,将相关状态存入具体观察者对象。具体主题角色又叫具体被观察者角色(ConcreteObservable)。
ConcreteObserver:具体观察者角色,实现抽象观察者角色(observer)所需要的更新接口,以便使自己状态和主题状态相协调。
总结:通过依赖抽象而不是依赖具体类,去实现一个类中某个状态的改变,而通知相关的一些类去做出相应的改变,进而保持同步状态。实现这样的方式或许有很多种,但是为了使系统能够易于复用,应该选择第耦合度的方案。减少对象之间的耦合度有利于系统的复用,在保证低耦合度的前提下并且能够维持行动的协调一致,保证高度协作,观察者模式是一种很好的设计方案。