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