欢迎来到天天文库
浏览记录
ID:43809437
大小:172.00 KB
页数:17页
时间:2019-10-14
《软件体系结构与设计模式 第11章__中介者模式》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、第十二章中介者模式9/16/20211中介者模式用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显示地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。MediatorPatternDefineanobjectthatencapsulateshowasetofobjectsinteract.Mediatorpromotesloosecouplingbykeepingobjectsfromreferringtoeachotherexplicitly,anditletsyouvarytheirinte
2、ractionindependently.一、概述9/16/20213中介者模式是封装一系列的对象交互的成熟模式,其关键是将对象之间的交互封装在称作中介者的对象中,中介者使各对象不需要显示地相互引用,这些对象只包含中介者的引用。当系统中某个对象需要和系统中另外一个对象交互时,只需将自己的请求通知中介者即可。二、中介者模式的结构与使用9/16/20214模式的结构中包括四种角色:中介者(Mediator)具体中介者(ConcreteMediator)同事(Colleague)具体同事(ConcreteColleague)
3、9/16/20215模式的UML类图模式的结构的描述与使用古代相互交战的A,B,C三方,想通过一个中介者调停之间的战火。A方委托调停者转达的信息是:“要求B方归还曾抢夺的100斤土豆,要求C方归还曾抢夺的20头牛”;B方委托调停者转达的信息是:“要求A方归还曾抢夺的10只鸡,要求C方归还曾抢夺的15匹马”;C方委托调停者转达的信息是:“要求A方归还曾抢夺的300斤小麦,要求B方归还曾抢夺的50头驴”。9/16/202181.同事(Colleague):Colleague.javapublicinterfaceColle
4、ague{publicvoidgiveMess(String[]mess);publicvoidreceiverMess(Stringmess);publicvoidsetName(Stringname);publicStringgetName();}注:本问题中,只需要一个具体中介者,我们并不需要一个中介者(Mediator)接口。9/16/202192.具体中介者(Mediator):ConcreteMediator.javapublicclassConcreteMediator{ColleagueAcolleag
5、ueA;ColleagueBcolleagueB;ColleagueCcolleagueC;publicvoidregisterColleagueA(ColleagueAcolleagueA){this.colleagueA=colleagueA;}publicvoidregisterColleagueB(ColleagueBcolleagueB){this.colleagueB=colleagueB;}publicvoidregisterColleagueC(ColleagueCcolleagueC){this.co
6、lleagueC=colleagueC;}publicvoiddeliverMess(Colleaguecolleague,String[]mess){if(colleague==colleagueA){if(mess.length>=2){colleagueB.receiverMess(colleague.getName()+mess[0]);colleagueC.receiverMess(colleague.getName()+mess[1]);}}elseif(colleague==colleagueB){if(
7、mess.length>=2){colleagueA.receiverMess(colleague.getName()+mess[0]);colleagueC.receiverMess(colleague.getName()+mess[1]);}}elseif(colleague==colleagueC){if(mess.length>=2){colleagueA.receiverMess(colleague.getName()+mess[0]);colleagueB.receiverMess(colleague.ge
8、tName()+mess[1]);}}}}9/16/2021113.具体同事(ConcreteColleague)_1:ColleagueA.javapublicclassColleagueAimplementsColleague{ConcreteMediatormediator;Stringname;ColleagueA(Con
此文档下载收益归作者所有