Observer Pattern Class Diagram
--觀察者模式也稱監聽器模式
-- 當我們對某一個對象的某一些狀態感興趣時,希望在任何時刻獲取其狀態的改變,比如數據的改變,網絡狀態的改變,此時,就需要使用觀察者模式。
--Observer pattern is one of the behavioral design pattern. Observer design pattern is useful when you are interested in the state of an object and** want to get notified whenever there is any change. **
--Subject:被觀察或者是被監聽的對象,比如Android中的UI控件:一個Button,或者是一個區內的WiFi連接
--Subject contains a list of observers to notify of any change in it’s state, so it should provide methods using which observers can register and unregister themselves. Subject also contain a method to notify all the observers of any change and either it can send the update while notifying the observer or it can provide another method to get the update.
--Subject包含了一些觀察者(監聽者),并提供一些接口供add和removeListener,另外包含一些供客戶端使用的方法通知各listener其自身狀態發生了改變。
--Observer||Listener:用于監聽subject的一些狀態,比如數據的增加,數據的修改,數據的刪除
--Observer||Listener一般自定義一個Listener的接口,包含了若干個想監聽的方法,在客戶端使用匿名內部類的方式add進subject中去。
例子:
subject.class{
private Data mdata;//01
private ArrayList<Listener> mListeners;//02
//observer.interface: //03
private interface Listener{
public void onDataAdded();
public void onDataRemoved();
public void onDataChanged();
....other methods.....
}
//following methods are provided for Observers;//04
public void addListener(Listener l){};
public void removeListener(Listener l){};
public void clearListeners(){};
//following methods are used to notify observers of change of subject dataSteted://05
public void DataAdd();
public void DataChanged();
public void DataRemoved();
}
標注:
--01:表示subject被觀察者擁有的數據
--02:表示一個容器用于裝載Observer
--03:定義了一個內部接口Observer,包含了若干個對subject的狀態的監聽
--04:subject提供的一些接口:供客戶端添加和移除Observer
--05:供客戶端調用當狀態發生改變時通知所有的Observer