資源描述:
《觀察者模式--java設(shè)計(jì)模式》由會(huì)員上傳分享,免費(fèi)在線閱讀,更多相關(guān)內(nèi)容在工程資料-天天文庫。
1、觀察者模式一Java設(shè)計(jì)模式觀察者模式定義:定義了對(duì)象之間的一對(duì)多的依賴,這樣一來,當(dāng)一個(gè)對(duì)象發(fā)生改變狀態(tài)的觀察者設(shè)計(jì)模式也叫發(fā)布-訂閱模式。也可以稱作:出版者+訂閱者=觀察者模忒在Android中觀察者模式的實(shí)例存:廣播機(jī)制,ContentObscrver的注冊(cè)方式,一個(gè)是同步的觀察者模式,一個(gè)足異步的觀察者模式。當(dāng)兩個(gè)對(duì)象之間松耦合,它們依然可以交互,俏是不清楚彼此的細(xì)節(jié),觀察者提供了一種對(duì)象的設(shè)計(jì),可以降低之叫的耦合,避免對(duì)象的雙14依賴。舉例:在Android中很多的Listener是觀察者模式,比如點(diǎn)1;?事件的OnClickListener,就
2、是為了避免對(duì)象的雙句依賴。一-先來看看Java源碼中的觀察者模式:Observer觀察者接口:packagecom.darning.java.observer;publicinterfaceObserver{voidupdate(Observableobservable,Objectarg);對(duì)象Observable類的實(shí)現(xiàn)packagecom.darning.java.observer;importjava.util.Vector;publicclassObservable{privatebooleanchanged=false;privateVecto
3、robs;publicObservable(){obs=newVector();123456publicsynchronizedvoidaddObserver(Observero){if(o==null)thrownewNullPointerException();if(!obs?contains(o)){obs?addElement(o);}}publicsynchronizedvoiddeleteObserver(Observero)obs?removeElement(o);publicvoidnotifyObservers(){notifyObser
4、vers(null);publicvoidnotifyObservers(Objectarg){Object[]arrLocal;synchronized(this){if(!changed)return;arrLocal=obs.toArray();clearChanged();for(inti=arrLocal.length-1;i〉=0;i--)((Observer)arrLocal[i]).update(this,arg);publicsynchronizedvoiddeleteObservers(){obs.removeAllElements()
5、;protectedsynchronizedvoidsetChanged(){changed=true;protectedsynchronizedvoidclearChanged(){changed=false;}publicsynchronizedbooleanhasChanged(){returnchanged;}*Returnsthenumberofobserversofthis0bservableobject.*?returnthenumberofobserversofthisobject?*/publicsynchronized
6、intcountObservers(){returnobs.size();參1參2?3?4參5參6參7?8?9?10?11參12?13參14?15?16參17?18參19?20?21參22?23參24?25?26參27?28參29參30參31參32參33?34參35參36參37參38?39參40參41參42參43?44參45參46參47參48?49參50參51參52參53?54參55參56參57參58?59參60參61參62參63?64參65參66參67參68?69參70MyObserver觀察者對(duì)象的實(shí)現(xiàn)packagecom.darning.java.o
7、bserver;publicclassMyObserverimplementsObserver{?Overridepublicvoidupdate(Observableobservable,Objectarg){System.out.printIn(nobservable:n+observable+Harg:11+arg);123456789MyObserver2觀察者對(duì)象的實(shí)現(xiàn)packagecom.darning?java?observer;publicclassMy0bserver2implementsObserver{@Overridepublicv
8、oidupdate(Observableobservable,Ob