上一篇博文中介紹了觀察者模式,並且實現了“推”的方式的代碼,但是關於“拉”模式的介紹很少,網上很多材料介紹的拉模式其實根本不是觀察者模式,下面通過一些分析來看看JDK裡面是怎麼實現的
本書介紹了Java 中內建的觀察者模式:
import java.util.Observable;import java.util.Observer;public class WeatherData extends Observable{private float temperature;private float humidity;private float pressure;//在這裡我們不需要追蹤觀察者了,也不需要管理註冊與刪除(讓超類代勞即可).//把註冊、添加、通知的相關代碼刪除public WeatherData(){//我們的構造器不再需要為了記住觀察者們而建立資料結構了}public void measurementsChanged(){setChanged();notifyObservers();}public void setMeasurements(float temperature,float humidity,float pressure){this.temperature = temperature;this.humidity = humidity;this.pressure = pressure;measurementsChanged();}public float getTemperature(){return temperature;}public float getHumidity(){return humidity;}public float getPressure(){return pressure;}}
import java.util.Observable;import java.util.Observer;public class CurrentConditionsDisplay implements Observer{Observable observable;private float temperature;private float humidity;public CurrentConditionsDisplay(Observable observable){this.observable = observable;observable.addObserver(this);}@Overridepublic void update(Observable obs, Object arg) {// TODO Auto-generated method stubif(obs instanceof WeatherData){WeatherData weatherData = (WeatherData) obs;this.temperature = weatherData.getTemperature();this.humidity = weatherData.getHumidity();display();}}public void display(){System.out.println("Current conditions:" + temperature + "F degrees and " + humidity + "% humidity");}}
public class Test {public static void main(String[] arg){WeatherData weatherData = new WeatherData();CurrentConditionsDisplay currentConditionsDisplay = new CurrentConditionsDisplay(weatherData);weatherData.setMeasurements(80, 65, 30.4f);weatherData.setMeasurements(82,70,29.2f);}}
結果是和之前相同的。
開始的時候我看到這裡就沒有完全搞懂:
假如Subject 的內容發生了變化,那麼它就改變標誌位。觀察者採用拉的方式從Subject 取得資料。想不明白的一件事情是:觀察者怎麼立即知道Subject 有變化?我自己YY了一種實現。就是當Subject 發生變化時,不需要通知觀察者,但是要讓Observer 進行Update。這就像訂報紙,報紙每天更新之後放到信箱裡面去,訂報人想起來的時候,去信箱看一下,假若有新的報紙,那麼訊息就傳出來了。但是,這種想法有些局限1)時效性,不能在發生變化的同時更新
2)每一個觀察者都需要一個線程,來定時的擷取資訊。
這是與觀察者模式出發點是不同的,有些部落格上說是另外一種模式,可能有它的應用情境。
後來問了一下同學,查看JDK中的代碼,發現其內部的實現和推的模式是類似的,也是有一個結構來維護Subject要通知的對象。只是現在當Subject 裡面調用notifyObserver 的時候會帶著Subject 的引用,Observer 需要根據這個引用再多走一步去Subject裡面取得自己所需要的資料
/* * Copyright (c) 1994, 2004, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */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 is 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 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(); }}
/* * Copyright (c) 1994, 1998, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */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);}
“推”的方式是指,Subject維護一份觀察者的列表,每當有更新發生,Subject會把更新訊息主動推送到各個Observer去。“拉”的方式是指,Subject 變化時給Observer 一個通知,然後由Observer自行決定用合適的方式去Subject擷取相應的更新資料。
“推”的好處包括:
1、高效。如果沒有更新發生,不會有任何更新訊息推送的動作,即每次訊息推送都發生在確確實實的更新事件之後,都是有意義的。
2、即時。事件發生後的第一時間即可觸發通知操作。
3、可以由Subject確立通知的時間,可以避開一些繁忙時間。
4、可以表達出不同事件發生的先後順序。
“拉”的好處包括:
1、Observer可以不理會它不關心的變更事件,只需要去擷取自己感興趣的事件即可。
2、Observer可以自行決定擷取更新事件的時間和方式。
3、拉的形式可以讓Subject更好地控制各個Observer每次查詢更新的存取權限,因為Observer 是利用Subject 的getter方法來擷取資料。