第18章.设计模式_第1页
第18章.设计模式_第2页
第18章.设计模式_第3页
第18章.设计模式_第4页
第18章.设计模式_第5页
已阅读5页,还剩32页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

实战java程序设计课后答案第十八章设计模式 选择题AB ABCBD简答题1.设计模式分为几类?每类中又包含哪些设计模式?答:设计模式分为三种类型,共23个。

一、创建型模式:单例模式、抽象工厂模式、建造者模式、工厂模式、原型模式。二、结构型模式:适配器模式、桥接模式、装饰模式、组合模式、外观模式、享元模式、代理模式。三、行为型模式:模版方法模式、命令模式、迭代器模式、观察者模式、中介者模式、备忘录模式、解释器模式、状态模式、策略模式、职责链模式、访问者模式。2.单例模式的作用及应用场景。作用:让一个类只能创建一个实例(因为频繁的创建对象,回收对象会造成系统性能下降。)。解决对象的唯一性,保证了内存中一个对象是唯一的

应用场景:当前对象的创建比较消耗资源,我们在使用这个对象时只需要有一个就可以应用。这个时候就可以将其设计成单例的模式。在一定的场景中,只有一个这样的实例,比如说银行的号码管理器等。java连接数据库,与数据库的连接会比较消耗资源。我们可以将其做成单例的,

这个时候在内存中就有一个,所有人操作的都是一个。观察者模式的作用及应用场景。作用:观察者模式是对象的行为模式,又叫发布-订阅(Publish/Subscribe)模式、模型-视图(Model/View)模式、源-监听器(Source/Listener)模式或从属者(Dependents)模式。观察者模式定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态上发生变化时,会通知所有观察者对象,使它们能够自动更新自己。应用场景:1、对一个对象状态的更新,需要其他对象同步更新,而且其他对象的数量动态可变。

2、对象仅需要将自己的更新通知给其他对象而不需要知道其他对象的细节代理模式的作用及应用场景作用:为其他对象提供一种代理以控制对这个对象的访问。在某些情况下,一个对象不适合或者不能直接引用另一个对象,而代理对象可以在客户端和目标对象之间起到中介作用。应用:如果我们要买一辆轿车必须通过汽车4S店,汽车4s店就是充当代理角色,其目的就是控制买车客户的买车行为,必须通过汽车4S店才能从汽车厂商买一辆车。编码题尽可能写出你知道的设计模式:一、创建型模式:单例模式、抽象工厂模式、建造者模式、工厂模式、原型模式。二、结构型模式:适配器模式、桥接模式、装饰模式、组合模式、外观模式、享元模式、代理模式。三、行为型模式:模版方法模式、命令模式、迭代器模式、观察者模式、中介者模式、备忘录模式、解释器模式、状态模式、策略模式、职责链模式、访问者模式。2.模仿书中代理模式的示例,自己想一个生活中的案例,进行模仿。模拟气象站发送天气信息给布告板,然后布告板把天气信息显示在板上的例子publicinterfaceSubject{//观察者注册publicvoidregisterObserver(Observero);//删除观察者publicvoidremoveObserver(Observero);//当主题有内容更新时调用,用于通知观察者publicvoidnotifyObserver();} /** *观察者 */ publicinterfaceObserver{ //当气象站观测的天气发生变化时,主题会把参数值传给观察者 publicvoidupdate(floattemp); }/***用于布告板显示*/publicinterfaceDisplayElement{//在显示布告板上显示的操作publicvoiddisplay();}/***气象站实现主题,发布气象信息(气温)*/publicclassWeatherStationimplementsSubject{privateArrayListobservers;privatefloattemp;publicWeatherStation(){//加个ArrayList存放所有注册的Observer对象;observers=newArrayList<>();}@OverridepublicvoidregisterObserver(Observero){//当新的观察者注册时添加进来observers.add(o);}@OverridepublicvoidremoveObserver(Observero){//当观察者取消注册时去除该观察者inti=observers.indexOf(o);if(i>=0){observers.remove(i);}}@OverridepublicvoidnotifyObserver(){//更新状态,调用Observer的update告诉观察者有新的信息for(inti=0;i<observers.size();i++){Observerobserver=(Observer)observers.get(i);observer.update(temp);}}/**此方法用于气象站收到的数据,并且调用更新使数据实时通知给观察者*/publicvoidsetMeasurements(floattemp){this.temp=temp;System.out.println("气象站测量的温度为:"+temp+"℃");notifyObserver();}}/***布告板上的状态显示*/publicclassConditionDisplayimplementsObserver,DisplayElement{privatefloattemp;privateSubjectweatherStation;publicConditionDisplay(SubjectweatherStation){//构造时需要间主题/被观察者对象作为注册之用this.weatherStation=weatherStation;weatherStation.registerObserver(this);}@Overridepublicvoiddisplay(){//将数据显示在布告板上System.out.println("布告板显示当前温度为:"+temp+"℃");}@Overridepublicvoidupdate(floattemp){//接受来自主题/被观察者(气象站)的数据this.temp=temp;display();}}测试publicclassWeatherObserver{publicstaticvoidmain(String[]args){//首先创建一个主题/被观察者WeatherStationweatherStation=newWeatherStation();//创建观察者并将被观察者对象传入ConditionDisplayconditionDisplay=newConditionDisplay(weatherStation);//设置气象站模拟收到的气温数据weatherStation.setMeasurements(25);weatherStation.setMeasurements(24);weatherStation.setMeasurements(23);}}查资料,阅读AWT或Swing源码,完成模仿事件监听的代码。/***新建一个点击事件的接口Clickable.java。*只负责执行点击事件*/publicinterfaceClickable{//点击事件voidonClick();}/***监听器接口*@authorAdministrator**/publicinterfaceOnClickListener{voidonClick(Clickableclickable);}新建按钮Button模仿button的点击事件/***实现焦点监听*位置监听*颜色改变监听*/publicclassButtonimplementsClickable{ //使用集合管理监听器 privatestaticList<OnClickListener>onClickListeners=newArrayList<OnClickListener>(); /** *添加监听 *@paramonClickListener */ privatevoidaddClickListener(OnClickListeneronClickListener){ onClickListeners.add(onClickListener); } /** *移除监听 *@paramonClickListener */ privatevoidremove(OnClickListeneronClickListener){ onClickListeners.remove(onClickListener); } publicinterfaceOnClickListener{ publicvoidonClick(Clickableclickable); } //如果我们需要执行所有被监听对象工作的时候 @Override publicvoidonClick(){ for(OnClickListeneronClickListener:onClickListeners){ onClickListener.onClick(this); } } /** *颜色改变的监听器 */ publicstaticabstractclassOnColorListenerimplementsOnClickListener{ @Override publicvoidonClick(Clickableclickable){ if(true){ colorChanged(); } } publicabstractvoidcolorChanged(); } /** *设置监听器 * *@paramonClickListener */ publicvoidsetOnClickListener(OnClickListeneronClickListener){ if(onClickListener!=null){ onClickListener.onClick(this); } //添加到管理监听器的集合内 addClickListener(onClickListener); } /** *位置监听器 * *@authorAdministrator * */ publicstaticabstractclassOnCoordinateListenerimplementsOnClickListener{ @Override publicvoidonClick(Clickableclickable){ if(true){ coordinateChanged(); } } publicabstractvoidcoordinateChanged(); } /** *焦点监听器 *@authorAdministrator */ publicstaticabstractclassOnFocusListenerimplementsOnClickListener{ @Override publicvoidonClick(Clickableclickable){ if(true){ onFocusChanged(); } } publicabstractvoidonFocusChanged(); }}测试publicclassTest{ publicstaticvoidmain(String[]args){ Buttonbtn=newButton(); btn.setOnClickListener(newOnClickListener(){ @Override publicvoidonClick(Clickableclickable){ System.out.println("回调方法"); } }); newButton().setOnClickListener(newButton.OnColorListener(){ @Override publicvoidcolorChanged(){ System.out.println("颜色改变的监听"); } }); newButton().setOnClickListener(newButton.OnCoordinateListener(){ @Override publicvoidcoordinateChanged(){ System.out.println("位置改变监听"); } }); newButton().setOnClickListener(newButton.OnFocusListener(){ @Override publicvoidonFocusChanged(){ System.out.println("焦点改变的监听"); } }); }}4.查阅资料,模仿Spring框架的JDBCTemplate类,完成模仿代码。publicinterfaceIStatementCallback{publicObjectdoInStatement(Statementstmt)throwsRuntimeException,SQLException;}//模板模式模仿SpringJdbcTemplate类publicclassJdbcTemplate{ publicObjectexecute(IStatementCallbackaction){ Connectionconn=null; Statementstmt=null; Objectresult=null; try{ conn=this.getConnection(); conn.setAutoCommit(false); stmt=conn.createStatement(); //注意这一句 result=action.doInStatement(stmt); mit(); conn.setAutoCommit(true); }catch(SQLExceptione){ transactionRollback(conn);//进行事务回滚 e.printStackTrace(); thrownewRuntimeException(e); }finally{ this.closeStatement(stmt); this.closeConnection(conn); } returnresult; } /* *当发生异常时进行事务回滚 */ privatevoidtransactionRollback(Connectionconn){ if(conn!=null){ try{ conn.rollback(); }catch(SQLExceptione){ e.printStackTrace(); } } } //关闭打开的Statement privatevoidcloseStatement(Statementstmt){ if(stmt!=null){ try{ stmt.close(); stmt=null; }catch(SQLExceptione){ e.printStackTrace(); } } } //关闭打开的Connection privatevoidcloseConnection(Connectionconn){ if(conn!=null){ try{ conn.close(); conn=null; }catch(SQLExceptione){ e.printStackTrace(); } } } //取得一个Connction privateConnectiongetConnection(){ Stringdriver="com.mysql.jdbc.Driver"; Stringurl="jdbc:mysql:///sxt"; Connectionconn=null; try{ Class.forName(driver); conn=DriverManager.getConnection(url,"sxt","sxt"); }catch(ClassNotFoundExceptione){ e.printStackTrace(); }catch(SQLExceptione){ e.printStackTrace(); } returnconn; }}测试publicclassTest{ publicstaticvoidmain(String[]args){ newTest().testJdbcTemp(); } privatevoidtestJdbcTemp(){ JdbcTemplatejt=newJdbcTemplate();/**因为IStatementCallback是一个接口,所以我们在这里直接用一个匿名类来实现*如果已经正确的插入啦一条数据的话,它会正确的返回一个整数1*而我们这里的stmt是从JdbcTemplate中传过来的*/intcount=(Integer)jt.execute(newIStatementCallback(){publicObjectdoInStatement(Statementstmt)throwsRuntimeException,SQLException{Stringsql="INSERTINTOpersonVALUES(1,'sxt','sxt')";intresult=stmt.executeUpdate(sql);returnnewInteger(result);}});System.out.println("Count:"+count);//读取刚刚插入的数据jt.execute(newIStatementCallback(){publicObjectdoInStatement(Statementstmt)throwsRuntimeException,SQLException{Stringsql="SELECTname,passwordFROMpersonWHEREid=1";ResultSetrs=null;rs=stmt.executeQuery(sql);Personp=null;if(rs.next()){p=newPerson(rs.getString("name"),rs.getString("password"));System.out.println(p);}returnp;}}); }}以身边的场景出发,测试装饰器模式假设我们现在去咖啡店要了一杯咖啡,可以加奶、加糖等等。咖啡和奶、糖分别有不同的价格。

咖啡就是我们的组件,奶和糖是我们的装饰者,现在我们要计算调制这样一杯咖啡花费多少。publicinterfaceDrink{publicfloatcost();publicStringgetDescription();}publicclassCoffeeimplementsDrink{ finalprivateStringdescription="coffee";//每杯coffee售价10元 publicfloatcost(){return10;} publicStringgetDescription(){returndescription;}}//调味抽象类publicabstractclassCondimentDecoratorimplementsDrink{protectedDrinkdecoratorDrink;publicCondimentDecorator(DrinkdecoratorDrink){this.decoratorDrink=decoratorDrink;}publicfloatcost(){returndecoratorDrink.cost();}publicStringgetDescription(){returndecoratorDrink.getDescription();}}//装饰类牛奶publicclassMilkextendsCondimentDecorator{publicMilk(DrinkdecoratorDrink){super(decoratorDrink);}@Overridepublicfloatcost(){returnsuper.cost()+2;}@OverridepublicStringgetDescription(){returnsuper.getDescription()+"milk";}}/***装饰类糖*@authorAdministrator**/publicclassSugarextendsCondimentDecorator{publicSugar(DrinkdecoratorDrink){super(decoratorDrink);}@Overridepublicfloatcost(){returnsuper.cost()+1;}@OverridepublicStringgetDescription(){returnsuper.getDescription()+"sugar";}}//测试publicclassShop{ publicstaticvoidmain(String[]args){ //点一杯coffee Drinkdrink=newCoffee(); System.out.println(drink.getDescription()+":"+drink.cost()); //加一份奶 drink=newMilk(drink); System.out.println(drink.getDescription()+":"+drink.cost()); //加一份糖 drink=newSugar(drink); System.out.println(drink.getDescription()+":"+drink.cost()); //再加一份糖 drink=newSugar(drink); System.out.println(drink.getDescription()+":"+drink.cost()); }}使用责任链模式完成在公司中的审批流程。/***封装采购信息*/publicclassPurchaseRequest{ privatedoubleMoney; privateStringreason; privateStringname; publicdoublegetMoney(){ returnMoney; } publicvoidsetMoney(doublemoney){ Money=money; } publicPurchaseRequest(doublemoney,Stringreason,Stringname){ super(); Money=money; this.reason=reason; =name; } publicStringgetReason(){ returnreason; } publicvoidsetReason(Stringreason){ this.reason=reason; } publicStringgetName(){ returnname; } publicvoidsetName(Stringname){ =name; } publicPurchaseRequest(){ super(); } @Override publicStringtoString(){ return"PurchaseRequest[Money="+Money+",reason="+reason+",name="+name+"]"; }}/***抽象类*/publicabstractclassLeader{ protectedStringname; protectedLeadernextLeader; publicLeader(Stringname){ super(); =name; } /** *设定责任链上的后继对象 *@paramnextLeader */ publicvoidsetNextLeader(LeadernextLeader){ this.nextLeader=nextLeader; } publicabstractvoidhandleRequest(PurchaseRequestrequest);}//主任publicclassDirectorextendsLeader{ publicDirector(Stringname){ super(name); } @Override publicvoidhandleRequest(PurchaseRequestrequest){ if(request.getMoney()<5){ System.out.println("主任:"++"审批通过"); }else{ System.out.println("主任:金额超过限制,经理审批"); if(this.nextLeader!=null){ this.nextLeader.handleRequest(request); } } }}//经理publicclassManagerextendsLeader{ publicManager(Stringname){ super(name); //TODOAuto-generatedconstructorstub } @Override publicvoidhandleRequest(PurchaseRequestrequest){ if(request.getMoney()>=5&&request.getMoney()<10){ System.out.println("经理:"++"审批通过"); }else{ System.out.println("经理:金额超过限制,请副总经理审批"); if(this.nextLeader!=null){ this.nextLeader.handleRequest(request); } } }}//副总经理publicclassDeputyManagerextendsLeader{ publicDeputyManager(Stringname){ super(name); } @Override publicvoidhandleRequest(PurchaseRequestrequest){ if(request.getMoney()>=10&&request.getMoney()<20){ System.out.println("副总经理:"++"审批通过"); }else{ System.out.println("副总经理:金额超过限制,请总经理审批"); if(this.nextLeader!=null){ this.nextLeader.handleRequest(request); } } }}//总经理publicclassGeneralManagerextendsLeader{ publicGeneralManager(Stringname){ super(name); } @Override publicvoidhandleRequest(PurchaseRequestrequest){ if(request.getMoney()>=20){ System.out.println("总经理:"++"审批通过"); } }}//测试publicclassClient{ publicstaticvoidmain(String[]args){ Leaderl1=newDirector("李白"); Leaderl2=newManager("杜甫"); Leaderl3=newDeputyManager("白居易"); Leaderl4=newGeneralManager("武则天"); //组织责任链的对应关系 l1.setNextLeader(l2); l2.setNextLeader(l3); l3.setNextLeader(l4); //开始审批 PurchaseRequestp=newPurchaseRequest(25,"美国参加学术研讨会","王安石"); System.out.println("员工:"+p.getName()+",预知金额:"+p.getMoney()+"万元"+",原因是:"+p.getReason()); System.out.println("================开始审批==============="); l1.handleRequest(p); }}7.模拟富士康代工厂的场景,使用工厂模式创造:小米手机,苹果手机和OPPO手机产品接口publicinterfacePhone{ publicvoidstartWeChat();} 产品实现类 苹果手机publicclassIPhoneimplementsPhone{ @Override publicvoidstartWeChat(){ System.out.println("苹果手机正在运行微信程序"); }} 小米手机publicclassMIPhoneimplementsPhone{ @Override publicvoidstartWeChat(){ System.out.println("小米手机正在运行微信程序"); }} OPPO手机 publicclassOPPOPhoneimplementsPhone{ @Override publicvoidstartWeChat(){ System.out.println("OPPO手机正在运行微信程序"); }} 工厂接口 publicinterfaceFoxconnFatory{ publicPhoneproduceProcuct();} 工厂实现类 苹果工厂 publicclassFoxconnIPhoneFactoryimplementsFoxconnFatory{ @Override publicPhoneproduceProcuct(){ returnnewIPhone(); }} 小米工厂 publicclassFoxconnMIPhoneFactoryimplementsFoxconnFatory{ @Override publicPhoneproduceProcuct(){ returnnewMIPhone(); }} OPPO工厂 publicclassFoxconnOPPOPhoneFactoryimplementsFoxconnFatory{ @Override

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论