對視察者,很多開發(fā)者其實(shí)不陌生,在平常開發(fā)進(jìn)程中,這也是1個(gè)非常常見的設(shè)計(jì)模式,特別是Android小火伴,很多人都知道broadcast就是1個(gè)典型的視察者模式,還有最近很火的rxjava,響應(yīng)式編程中,視察者模式扮演著1個(gè)很重要的角色,但視察者模式具體是怎樣樣運(yùn)轉(zhuǎn)的,部份小火伴就有點(diǎn)模糊了。
先從平常生活中1個(gè)例子開始說起,在看電視的進(jìn)程中,我們常常看到1些抗日神劇中有這么1個(gè)劇情,鬼子進(jìn)村,在進(jìn)村的進(jìn)程中,總會有1些1些人透風(fēng)報(bào)信,然后通知村里的人能躲的躲,能藏的藏,能跑的跑,或中路再弄個(gè)埋伏,抓到了以后是手撕還是其它方式處理,在此就先不做討論。。。其實(shí)這個(gè)進(jìn)程中就是1個(gè)典型的視察者模式,下面,我們先看1下手撕鬼子的UML。
DevilsSubject.java
/**
*
* created by zm on 2016⑸⑵8
* 繼承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()獲得是不是產(chǎn)生改變,這里我們統(tǒng)1設(shè)置成改變,以便測試
this.setChanged();
this.notifyObservers(assault);
}
}
VillagerObserver.java
/**
*
* created by zm on 2016⑸⑵8
*
* 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();
//如果視察者與集合中已有的視察者不同,則向?qū)ο蟮囊暡煺呒刑砑哟艘暡煺摺?/span>
devilsSubject.addObserver(yes);
devilsSubject.addObserver(no);
devilsSubject.setAssault("前方有1坨鬼子來了");
devilsSubject.setAssault("鬼子見閻王了,在來村的路上就被村民手撕了");
//返回 Observable 對象的視察者數(shù)目
System.out.println(devilsSubject.countObservers());
System.out.println("................");
devilsSubject.deleteObserver(yes);
devilsSubject.setAssault("鬼子來了");
System.out.println(devilsSubject.countObservers());
}
}
運(yùn)行的結(jié)果:
前方有1坨鬼子來了
前方有1坨鬼子來了
鬼子見閻王了,在來村的路上就被村民手撕了
鬼子見閻王了,在來村的路上就被村民手撕了
Observable對象的視察者數(shù)目:2個(gè)
................
鬼子來了
Observable對象的視察者數(shù)目:1個(gè)
下面是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
根據(jù)源碼中最上部份的注釋,翻譯成中文后,大體的意思是此類是1個(gè)被視察者。它可以派生子類來表示1個(gè)利用程序想要視察的對象。1個(gè)可視察到的對象(observable)可以有1個(gè)或多個(gè)視察者(observer)。1個(gè)視察者可以是任何實(shí)現(xiàn)接口的視察者的對象。修改后可視察到的實(shí)例,利用程序調(diào)用notifyObservers方法使所有的視察者調(diào)用更新方法。通知的順序?qū)⑹俏粗付ǖ摹U堊⒁?這與線程通知機(jī)制無關(guān),完全獨(dú)立于類對象的等待和通知機(jī)制。當(dāng)1個(gè)可視察的對象是新創(chuàng)建的,它的視察是空的。當(dāng)且僅當(dāng)這個(gè)方法返回true,兩個(gè)視察者是同步的。
源碼中,起關(guān)鍵性作用的就是vector和changed,在observable實(shí)例化的時(shí)候,就初始化了1個(gè)空的vector,可以通過vector添加和移除vector操作后,當(dāng)observable產(chǎn)生改變時(shí),通過changed去判斷是不是通知,在我們的上述示例代碼中使用setChanged(),主要是由于第1次加入的時(shí)候,不會去調(diào)用observer的update方法,也就是changed為false,當(dāng)changed為false時(shí),直接從notifyObservers方法中return,只有changed為true的時(shí)候才通知刷新,刷新之前,重新把changed賦值為false,提取上述源碼中的關(guān)鍵代碼以下:
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就是1個(gè)接口,里面1個(gè)update方法,這個(gè)類沒太多需要解釋的,有點(diǎn)Java基礎(chǔ)的都可以明白。
現(xiàn)在1目了然了,Observer模式是1種行動模式,它的作用是當(dāng)1個(gè)對象的狀態(tài)產(chǎn)生改變的時(shí)候,能夠自動通知其他關(guān)聯(lián)對象,自動刷新對象狀態(tài)。Observer模式提供給關(guān)聯(lián)對象1種同步通訊的手段,使其某個(gè)對象與依賴它的其他對象之間保持狀態(tài)同步。
抽象主題角色(Subject)內(nèi)部其實(shí)就是1個(gè)Vector,在addObserver的時(shí)候,就把需要的視察者添加到Vector中。在deleteObserver的時(shí)候,就把傳進(jìn)來的視察者從容器中移除掉。主題角色又叫抽象被視察者角色(observable),1般用1個(gè)抽象類或接口來實(shí)現(xiàn)。
observable與observer是1種1對多的依賴關(guān)系,可讓多個(gè)視察者對象同時(shí)監(jiān)聽某1個(gè)主題對象。視察者模式有時(shí)被稱作發(fā)布/定閱模式(Publish/Subscribe),對這名稱很貼切的,就好比我們定閱了報(bào)紙,每次報(bào)社新報(bào)紙出版發(fā)售的時(shí)候,就會根據(jù)定閱的客戶逐一發(fā)報(bào)紙,通知客戶瀏覽。
ConcreteSubject:具體主題角色,將相干狀態(tài)存入具體視察者對象。具體主題角色又叫具體被視察者角色(ConcreteObservable)。
ConcreteObserver:具體視察者角色,實(shí)現(xiàn)抽象視察者角色(observer)所需要的更新接口,以便使自己狀態(tài)和主題狀態(tài)相調(diào)和。
總結(jié):通過依賴抽象而不是依賴具體類,去實(shí)現(xiàn)1個(gè)類中某個(gè)狀態(tài)的改變,而通知相干的1些類去做出相應(yīng)的改變,進(jìn)而保持同步狀態(tài)。實(shí)現(xiàn)這樣的方式也許有很多種,但是為了使系統(tǒng)能夠易于復(fù)用,應(yīng)當(dāng)選擇第耦合度的方案。減少對象之間的耦合度有益于系統(tǒng)的復(fù)用,在保證低耦合度的條件下并且能夠保持行動的調(diào)和1致,保證高度協(xié)作,視察者模式是1種很好的設(shè)計(jì)方案。