觀察者模式類圖
- 觀察者模式也稱監(jiān)聽(tīng)器模式
- 當(dāng)我們對(duì)某一個(gè)對(duì)象的某一些狀態(tài)感興趣時(shí)逗威,希望在任何時(shí)刻獲取其狀態(tài)的改變
- 比如數(shù)據(jù)的改變,網(wǎng)絡(luò)狀態(tài)的改變,此時(shí)趁舀,就需要使用觀察者模式。
--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. **
觀察者模式構(gòu)成要素
- Subject:被觀察者祝沸,一般來(lái)說(shuō)被觀察者自身具有某種屬性狀態(tài)矮烹,其狀態(tài)的改變對(duì)我們的應(yīng)用會(huì)有不同業(yè)務(wù)邏輯上的影響。
- 比如Android中的UI控件:一個(gè)Button罩锐,一個(gè)區(qū)內(nèi)的WiFi連接奉狈,容器內(nèi)的數(shù)量變動(dòng)
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包含了一些觀察者(監(jiān)聽(tīng)者),并提供一些接口供add和removeListener涩惑,另外包含一些供客戶端使用的方法通知各listener其自身狀態(tài)發(fā)生了改變仁期。
Observer||Listener:用于監(jiān)聽(tīng)subject的一些狀態(tài),比如數(shù)據(jù)的增加竭恬,數(shù)據(jù)的修改跛蛋,數(shù)據(jù)的刪除
Observer||Listener一般自定義一個(gè)Listener的接口,包含了若干個(gè)想監(jiān)聽(tīng)的方法痊硕,在客戶端使用匿名內(nèi)部類的方式add進(jìn)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();
}
標(biāo)注:
--01:表示subject被觀察者擁有的數(shù)據(jù)
--02:表示一個(gè)容器用于裝載Observer
--03:定義了一個(gè)內(nèi)部接口Observer岔绸,包含了若干個(gè)對(duì)subject的狀態(tài)的監(jiān)聽(tīng)
--04:subject提供的一些接口:供客戶端添加和移除Observer
--05:供客戶端調(diào)用當(dāng)狀態(tài)發(fā)生改變時(shí)通知所有的Observer