資源描述:
《設(shè)計模式之1 observer模式》由會員上傳分享,免費在線閱讀,更多相關(guān)內(nèi)容在工程資料-天天文庫。
1、設(shè)計模式總章:設(shè)計模式就是把簡單的問題復(fù)雜化,帶來的好處是系統(tǒng)的可擴展性。用了設(shè)計模式以后:復(fù)雜度增加開發(fā)成本增加維護成本降低設(shè)計模式的基本原則是,添加,而不是修改。1.什么叫分析?(確定需求是什么)分析就是要知道我要做什么。確定系統(tǒng)實現(xiàn)什么樣的功能。2.什么叫設(shè)計?(實現(xiàn)需求)設(shè)計就是我要怎么實現(xiàn)。設(shè)計就是多種實現(xiàn)的手段當(dāng)中選取一個。實現(xiàn)某個功能是使用什么樣的方式。用一個接口來封裝一系列共同具有的特點。各個監(jiān)聽類都去實現(xiàn)這個接口。在被監(jiān)聽的類上加上addxxxlistener方法。awt當(dāng)中的事件:事件源可以是,but
2、tion,textField,textArea事件是:ActionEvent相對應(yīng)的監(jiān)聽器是actionlistener。通過配置文件來管理observer。配置文件:文件名:observer.properties文件的內(nèi)容:observers=com.bjsxt.dp.observer.Dad,com.bjsxt.dp.observer.GrandFather,com.bjsxt.dp.observer.Dog訪問當(dāng)前配置的文件的main方法:packagecom.bjsxt.dp.observer;importjav
3、a.io.IOException;importjava.util.ArrayList;importjava.util.List;importjava.util.Properties;//事件類classWakenUpEvent{privatelongtime;privateStringloc;privateChildsource;//事件方法publicWakenUpEvent(longtime,Stringloc,Childsource){super();this.time=time;this.loc=loc;this
4、.source=source;}publiclonggetTime(){returntime;}publicvoidsetTime(longtime){this.time=time;}publicStringgetLoc(){returnloc;}publicvoidsetLoc(Stringloc){this.loc=loc;}publicChildgetSource(){returnsource;}publicvoidsetSource(Childsource){this.source=source;}}//被監(jiān)聽類
5、。classChildimplementsRunnable{privateListwakenUpListeners=newArrayList();publicvoidaddWakenUpListener(WakenUpListenerl){wakenUpListeners.add(l);}voidwakeUp(){for(inti=0;i6、ners.get(i);l.ActionToWakenUp(newWakenUpEvent(System.currentTimeMillis(),"bed",this));}}publicvoidrun(){try{Thread.sleep(5000);}catch(InterruptedExceptione){e.printStackTrace();}this.wakeUp();}}//監(jiān)聽類classDadimplementsWakenUpListener{publicvoidActionToWakenUp(Wake
7、nUpEventwakenUpEvent){System.out.println("feedchild");}}//監(jiān)聽類classGrandFatherimplementsWakenUpListener{publicvoidActionToWakenUp(WakenUpEventwakenUpEvent){System.out.println("hugchild");}}//監(jiān)聽類classDogimplementsWakenUpListener{publicvoidActionToWakenUp(WakenUpEve
8、ntarg0){System.out.println("wangwang...");}}//監(jiān)聽接口interfaceWakenUpListener{publicvoidActionToWakenUp(WakenUpEventwakenUpEvent);}//主類publicclassTest{publicstati