设计模式——中介者模式

来源:互联网 发布:网络小额度贷款 编辑:程序博客网 时间:2024/05/17 02:38

用一个中介对象来封装一系列的对象交互。中介是各个对象不需要现实的相互引用。从而使其耦合松散。而且可以独立的改变他们之间的交互

角色:

Mediator:中介者接口。在里面定义了各个同事之间相互交互所需要的方法,可以是公共的方法,如Change方法,也可以是小范围的交互方法。

ConcreteMediator:具体的中介者实现对象。它需要了解并为维护每个同事对象,并负责具体的协调各个同事对象的交互关系。

Colleague:同事类的定义,通常实现成为抽象类,主要负责约束同事对象的类型,并实现一些具体同事类之间的公共功能,比如,每个具体同事类都应该知道中介者对象,也就是每个同事对象都会持有中介者对象的引用,这个功能可定义在这个类中。

ConcreteColleague:具体的同事类,实现自己的业务,需要与其他同事对象交互时,就通知中介对象,中介对象会负责后续的交互。


类图:


代码:

 美国和伊拉克通过联合国通话

package com.sun.mediator.cg;/** * 国家抽象 * @author work * */public abstract class Country {protected UnitedNations unitedNations;public Country(UnitedNations unitedNations) {this.unitedNations = unitedNations;}}

package com.sun.mediator.cg;/** * 联合国抽象类 * @author work * */public abstract class UnitedNations {public abstract void declare(String message,Country c);}

package com.sun.mediator.cg;/** * 美国 * @author work * */public class USA extends Country {public USA(UnitedNations unitedNations) {super(unitedNations);// TODO Auto-generated constructor stub}public void declare(String message) {// TODO Auto-generated method stubunitedNations.declare(message, this);}public void getMessage(String message) {System.out.println("美方获得情报:。。。。。。。。。"+message);}}

package com.sun.mediator.cg;/** * 伊拉克 * @author work * */public class Iraq extends Country{public Iraq(UnitedNations unitedNations) {super(unitedNations);// TODO Auto-generated constructor stub}public void declare(String message) {// TODO Auto-generated method stubunitedNations.declare(message, this);}public void getMessage(String message) {System.out.println("伊拉克获得情报:。。。。。。。。。"+message);}}

package com.sun.mediator.cg;/** * 联合国 * @author work * */public class UnitedNationsSc extends UnitedNations{private USA usa;private Iraq iraq;public Country getUsa() {return usa;}public void setUsa(USA usa) {this.usa = usa;}public Country getIraq() {return iraq;}public void setIraq(Iraq iraq) {this.iraq = iraq;}@Overridepublic void declare(String message, Country c) {// TODO Auto-generated method stubif(c==usa){iraq.getMessage(message);} if(c==iraq) {usa.getMessage(message);}}}

客户端

package com.sun.mediator.cg;public class Client {public static void main(String[] args) {UnitedNationsSc uns = new UnitedNationsSc();USA usa = new USA(uns);Iraq iraq = new Iraq(uns);uns.setUsa(usa);uns.setIraq(iraq);usa.declare("核武器必须禁止其它国家拥有");iraq.declare("木有核武器,你打我我也不怕");}}

输出:

伊拉克获得情报:。。。。。。。。。核武器必须禁止其它国家拥有
美方获得情报:。。。。。。。。。木有核武器,你打我我也不怕


ps:中介对象主要是用来封装行为的,行为的参与者就是那些对象,但是通过中介者,这些对象不用相互知道

0 0