1. 程式人生 > >Android中觀察者模式(Observable)的理解

Android中觀察者模式(Observable)的理解

對於觀察者模式還是第一次接觸,今天在上網看了些資料瞭解了一下,大意瞭解了……

定義:“定義物件間的一種一對多的依賴關係,當一個物件的狀態發生改變的時候,所有依賴於它的物件都將得到通知,並自動更新”,這就是所謂的觀察者模式,照意思理解那麼就一定會有觀察者和被觀察者了,在Java1.2之後,提供了兩個類,即Observable被觀察者,Observer觀察者;

在Android中也提供了一個類Observable用於觀察者模式,下面看看Observable 的原始碼便可以大意理解了。

/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.database;

import java.util.ArrayList;

/**
 * Provides methods for (un)registering arbitrary observers in an ArrayList.
 */
public abstract class Observable<T> {
    /**
     * The list of observers.  An observer can be in the list at most
     * once and will never be null.
     */
    protected final ArrayList<T> mObservers = new ArrayList<T>();

    /**
     * Adds an observer to the list. The observer cannot be null and it must not already
     * be registered.
     * @param observer the observer to register
     * @throws IllegalArgumentException the observer is null
     * @throws IllegalStateException the observer is already registered
     */
    public void registerObserver(T observer) {
        if (observer == null) {
            throw new IllegalArgumentException("The observer is null.");
        }
        synchronized(mObservers) {
            if (mObservers.contains(observer)) {
                throw new IllegalStateException("Observer " + observer + " is already registered.");
            }
            mObservers.add(observer);
        }
    }

    /**
     * Removes a previously registered observer. The observer must not be null and it
     * must already have been registered.
     * @param observer the observer to unregister
     * @throws IllegalArgumentException the observer is null
     * @throws IllegalStateException the observer is not yet registered
     */
    public void unregisterObserver(T observer) {
        if (observer == null) {
            throw new IllegalArgumentException("The observer is null.");
        }
        synchronized(mObservers) {
            int index = mObservers.indexOf(observer);
            if (index == -1) {
                throw new IllegalStateException("Observer " + observer + " was not registered.");
            }
            mObservers.remove(index);
        }
    }
    
    /**
     * Remove all registered observer
     */
    public void unregisterAll() {
        synchronized(mObservers) {
            mObservers.clear();
        }        
    }
}

當然這個類只是抽象類,如果我們需要用的話,還需要繼承 這個類,這有一個方法,通知被觀察者進行更新。

觀察者模式是軟體設計模式的一種。在此種模式中,一個目標物件管理所有相依於它的觀察者物件,並且在它本身的狀態改變時主動發出通知。

實現過程:“註冊——通知——撤銷註冊”

1、觀察者

(Observer)將自己註冊到被觀察物件(Subject)中,被觀察物件將觀察者存放在一個容器(Container)裡。

2、被觀察物件

被觀察物件發生了某種變化,從容器中得到所有註冊過的觀察者,將變化通知觀察者。

在Android中最常用的應用:

在ListView中Adapter中favoritesAdapter.registerDataSetObserver(mDataSetObserver);;資料改變之後會自動呼叫:

mDataSetObserver裡面的方法;如:

DataSetObserver mDataSetObserver = new DataSetObserver() {

		@Override
		public void onChanged() {
			if (favoritesAdapter.getCount() <= 0) {
				showNoDeviceHint();
			} else {
				hiddenNoDeviceHint();
			}
			loadingImageButton.setVisibility(View.GONE);
			super.onChanged();
		}

		@Override
		public void onInvalidated() {
			super.onInvalidated();
		}

	};