欢迎来到天天文库
浏览记录
ID:47239769
大小:56.50 KB
页数:7页
时间:2019-08-05
《实验九+观察者模式、策略模式》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、实验九淘宝店号530213一、实验目的1、熟练掌握观察值模式、策略模式的建模方式2、掌握如何应用观察值模式、策略模式编程解决具体问题二、实验器材1、计算机一台2、JCreator软件实验内容1、以红绿灯为例,用观察值模式模拟实现现实生活中行人、车辆以及红绿灯之间的关系2、设计一个网上书店,该系统中所有的计算机类图书(ComputerBook)每本都有10%的折扣,所有语言类图书(LanguageBook)每本都有2元的折扣,小说类图书(NovelBook)每100元有10元的折扣。现使用策略模式来设计该系统,绘制类图并编程实现。三、实验结果程序代码:(1)观察者模式代码packagecom
2、.zfs.pojo;publicclassClient{publicstaticvoidmain(String[]args){TrafficLightroad=newRoadLight();TrafficLightwalk=newWalkerLight();TrafficObservewalker=newWalker();TrafficObservevehicle=newVehicle();road.attach(vehicle);walk.attach(walker);road.changeColor();walk.changeColor();System.out.println("--
3、-------------");road.changeColor();walk.changeColor();}}packagecom.zfs.pojo;importjava.awt.Color;publicclassRoadLightextendsTrafficLight{publicRoadLight(){this.color="red";}@OverridepublicvoidchangeColor(){if(this.color.equals("red")){this.color="green";}else{this.color="red";}for(Objectobs:observ
4、ers){((TrafficObserve)obs).response(this.color);}}}packagecom.zfs.pojo;importjava.awt.Color;importjava.util.ArrayList;publicabstractclassTrafficLight{protectedStringcolor;protectedArrayListobservers=newArrayList();publicabstractvoidchangeColor();publicvoidattach(Tra
5、fficObserveobs){observers.add(obs);}publicvoidremove(TrafficObserveobs){observers.remove(obs);}}packagecom.zfs.pojo;publicinterfaceTrafficObserve{publicvoidresponse(Stringcolor);}packagecom.zfs.pojo;publicclassVehicleimplementsTrafficObserve{@Overridepublicvoidresponse(Stringcolor){if(color.equals
6、("red")){System.out.println("车灯变红,车辆请等待");}else{System.out.println("车灯变绿,车辆可以通行");}}}packagecom.zfs.pojo;publicclassWalkerimplementsTrafficObserve{@Overridepublicvoidresponse(Stringcolor){if(color.equals("red")){System.out.println("行人灯变红,行人请等待");}else{System.out.println("行人灯变绿,行人可以通行");}}}packagec
7、om.zfs.pojo;publicclassWalkerLightextendsTrafficLight{publicWalkerLight(){this.color="green";}@OverridepublicvoidchangeColor(){if(this.color.equals("red")){this.color="green";}else{this.color="red";}for(Objectobs
此文档下载收益归作者所有