欢迎来到天天文库
浏览记录
ID:50225559
大小:71.50 KB
页数:11页
时间:2020-03-06
《观察者模式 简单例子.doc》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、实验五、观测者模式(4学时)【实验目的】1、了解观测者模式的应用场景、目的和解决问题的方法。2、掌握观测者模式的结构、各角色之间的协作过程和代码实现。3、了解观测者模式的应用。【实验性质】验证性实验【实验内容与步骤】1、用Java或C#语言实现观测者模式的结构,并用代码说明客户端程序如何应用观测者模式。观察者publicinterfaceObserver{publicvoidupdate();}具体观察者publicclassConcreteObserverimplementsObserver{
2、privateSubjectmConcretcSubject;publicConcreteObserver(SubjectmConcreteSubject){this.mConcreteSubject=mConcreteSubject;}publicvoidupdate(){Systcm.out・printin:,,+mConcreteSubject・getInformation());}}主题publicinterfaceSubject{publicvoidattach(Observero);
3、publicvoiddetach(Observero);publicStringgetlnformationO;publicvoidnotifyObservers();publicStringsetInformation(Strings);}具体主题importjava.util.ArrayList;publicclassConcreteSubjectimplementsSubject{publicArrayList〈Observer〉mObserver;privateStringlnforma
4、tion=,zz,;privateObjectmState;publicConcreteSubject(){mObserver^newArrayList();ijpublicObjectgetState(){returnmState;}publicvoidsetState(Objectval){mState^val;}publicvoidattach(Observero){if(o!=null)mObserver.add(o);}publicvoiddetach(Observ
5、ero){if(mObserver・contains(o))mObserver・remove(o);publicStringsetinformation(Strings){lnformat.ion=s;returns;}publicStringgetTnformatio门(){returnInformation;}publicvoidnotifyObscrvers(){for(inti=0;i6、update();}}}客户端publicclassApplication{publicstaticvoidnuiin(String[]args)Subjects=newConcreteSubject();Observerol=newConcreteObserver(s);Observero2=newConcreteObserver(s);s.attach(o2);s.attach(ol);s.setinformation(,z你好");s・notifyObservets();}}2、请用观测者7、模式实现一个汽车驾驶室仪表系统,当汽车改变速度、改变方向时实时显示汽车的速度、方向、指示灯等信息。观察者速度表packagedriver;importjaaut订.Observable;importjaaut订.Observer;importjava・awt・*;importjava・awt.event・*;importjavax.swing.*;publicclassSpeedAimplementsObserver{JTextFieldtext二newJTextField("");Obse8、rvableo;intspeed二0;publieSpeedA(Observableo){text・setVisible(t.rue);this・o=o;o.addObserver(this);jpublicJTextFieldgetText(){returntext;}publicvoidupdate(Observableo,Objectarg){if(oinstanceofcar){carc=newcar();c=(car)o;speed二c.getspeed();text.setTextC
6、update();}}}客户端publicclassApplication{publicstaticvoidnuiin(String[]args)Subjects=newConcreteSubject();Observerol=newConcreteObserver(s);Observero2=newConcreteObserver(s);s.attach(o2);s.attach(ol);s.setinformation(,z你好");s・notifyObservets();}}2、请用观测者
7、模式实现一个汽车驾驶室仪表系统,当汽车改变速度、改变方向时实时显示汽车的速度、方向、指示灯等信息。观察者速度表packagedriver;importjaaut订.Observable;importjaaut订.Observer;importjava・awt・*;importjava・awt.event・*;importjavax.swing.*;publicclassSpeedAimplementsObserver{JTextFieldtext二newJTextField("");Obse
8、rvableo;intspeed二0;publieSpeedA(Observableo){text・setVisible(t.rue);this・o=o;o.addObserver(this);jpublicJTextFieldgetText(){returntext;}publicvoidupdate(Observableo,Objectarg){if(oinstanceofcar){carc=newcar();c=(car)o;speed二c.getspeed();text.setTextC
此文档下载收益归作者所有