java.util.Observable 和java.util.Observer的源碼分析

對於觀察者模式,其實Java已經爲我們提供了已有的接口和類。Java中的訂閱者(Subscribe,觀察者)就是類java.util.Observer,java中的通知治者(Publish,發佈者)就是java.util .Observable

使用步驟:

1)創建 被觀察者對象Observable mObservable ,創建觀察者對象 Observer mObserver, 爲被觀察者添加觀察者mObservable.

addObserver(Observer o)

2) 被觀察有了狀態的改變,調用this.setChanged()和this.notifyObservers(state)

3) 觀察者將會自動調用update(Observable o, Object arg)進行邏輯判斷處理

package com.xuanyuan.basemodule.originalcode.java;

import java.util.Observable;
import java.util.Observer;
import java.util.Vector;

/**
 * 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>.
 *  一個可觀察對象可以具有一個或多個觀察者。觀察者可以是實現接口Observer的任何對象。
 * <p>
 * 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.
 * 在可觀察實例發生更改後,調用Observable.notifyObservers方法的應用程序將通過調用其update方法來通知其所有觀察者更改。
 *
 * <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.
 * Observable類中提供的默認實現將按照觀察者註冊興趣的順序通知觀察者,但是子類可以更改此順序、使用無保證順序、
 * 在單獨的線程上傳遞通知,或者可以保證它們的子類根據自己的選擇遵循此順序。
 *
 * <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>.
 * 注意,這個通知機制與線程無關,與類對象的wait和notify機制完全分離
 * <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 equals method returns true for them.
 * 當兩個觀察者通過 equals 方法放回true時,判定這個兩個觀察者是同一個
 * <p>
 * 1.Observable.notifyObservers()對應方法 Observer.update(java.util.Observable, java.lang.Object)
 * 2. this.setChanged(); 將狀態設置爲changed = true 後才能進行 this.notifyObservers(state),此時該方法才能真正有效
 */
public class Java_util_Observable extends Observable {
    private boolean changed = false;
    /**
     * 用於存儲觀察者
     */
    private Vector<Observer> obs;

    /**
     * Construct an Observable with zero Observers.
     */
    public Java_util_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.
     * 從該對象的觀察者集中刪除一個觀察者
     * <p>
     * Passing <CODE>null</CODE> to this method will have no effect.
     * 傳遞一個null ,對該方法無影響
     *
     * @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.
     * 如果此對象已更改,如<code>has changed</code>方法所示,則通知其所有觀察者,
     * 然後調用<code>clearChanged</code>方法以指示此對象已不再更改。只會通知觀察者一次
     * <p>
     * Each observer has its <code>update</code> method called with two arguments:
     * 每個觀察者都有其用兩個參數調用的<code>update</code>方法
     * <p>
     * this observable object and <code>null</code>. In other words, this method is equivalent to:
     * 這個可觀察對象和<code>null</code>。換句話說,這種方法相當於:
     * <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
             * 1) 新添加的觀察者將錯過正在進行的通知
             *
             * 2) a recently unregistered Observer will be wrongly notified when it doesn't care
             * 2) 一個最近未註冊的觀察者在不在乎的時候會被錯誤地通知
             */

            // Android-changed: Call out to hasChanged() to figure out if something changes.
            // Upstream code avoids calling the nonfinal hasChanged() from the synchronized block,
            // but that would break compatibility for apps that override that method.
            // Android changed:調用hasChanged()以確定是否有更改。上游代碼避免從synchronized塊調用nonfinal hasChanged(),
            // 但這將破壞覆蓋該方法的應用程序的兼容性。
            // if (!changed)
            if (!hasChanged())
                return;
            arrLocal = obs.toArray();
            //如果有改變將 changed=false,同時進行後面的操作
            clearChanged();
        }

        // 通知每個觀察者進行update操作
        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.
     * 指示此對象已不再更改,或已通知其所有觀察者其最近的更改,
     * 因此hasChanged方法現在將返回false此方法由notifyObservators方法自動調用。
     *
     * @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.
     * 被觀察者是否有數據的改變,有改變則通知觀察者update
     *
     * @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();
    }
}

class Java_util_Observer implements Observer {

    /**
     * 當 Observable對象調用notifyObservers(),會觸發觀察者的upDate方法。
     */
    @Override
    public void update(Observable o, Object arg) {

    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章