《大话设计模式--中介者(调停者)模式》笔记

1、中介者模式(Mediator),用一个中介对象来封装一系列的对象交互。中介者使得各个对象不需要显式的相互引用,从而使其耦合松散,而且可以独立的改变他们之间的交互。

2、中介者模式结构图
在这里插入图片描述
Colleague叫做抽象同时类,而ConcreteColleague是具体同事类,每个具体同事都只知道自己的行为,而不了解其他同事类的情况,但它们都认识中介者对象,Mediator是中介者对象,定义了同事对象到中介者对象的接口,ConcreteMediator是具体中介者,实现抽象方法,他需要知道所有的具体同事类,并从具体同事类接受消息,向具体同事对象发出命令。

3、简单代码实现
Meditor类,抽象中介者类

public abstract class Meditor {

	//发送消息的方法,得到同事对象和发送消息
	public abstract void send(String message,Colleague colleague);
}

Colleague类,抽象同事类

public class Colleague {
	
	protected Meditor meditor;
	
	//得到中介者
	public Colleague(Meditor meditor) {
		// TODO Auto-generated constructor stub
		this.meditor=meditor;
	}

}

ConcreteMeditor类,具体中介者类

public class ConcreteMeditor extends Meditor {
	
	private ConcreteColleague1 coll1;
	private ConcreteColleague2 coll2;

	
	public void setColl1(ConcreteColleague1 coll1) {
		this.coll1 = coll1;
	}


	public void setColl2(ConcreteColleague2 coll2) {
		this.coll2 = coll2;
	}


	@Override
	public void send(String message, Colleague colleague) {
		// TODO Auto-generated method stub
		if(colleague.equals(coll1)) {
			coll2.notify(message);
		}else {
			coll1.notify(message);
		}
		
		
	}

}

ConcreteColleague1和ConcreteColleague2,各种同事对象

public class ConcreteColleague1 extends Colleague {

	public ConcreteColleague1(Meditor meditor) {
		super(meditor);
		// TODO Auto-generated constructor stub
	}
	
	public void send(String message) {
		meditor.send(message, this);
	}

	public void notify(String message) {
		// TODO Auto-generated method stub
		System.out.println("同事1得到消息"+message);
	}

}

public class ConcreteColleague2 extends Colleague{

	public ConcreteColleague2(Meditor meditor) {
		super(meditor);
		// TODO Auto-generated constructor stub
	}
	
	public void send(String message) {
		meditor.send(message, this);
	}

	public void notify(String message) {
		// TODO Auto-generated method stub
		System.out.println("同事2得到消息"+message);
	}

}




客户端调用

public class Client {
	public static void main(String[] args) {
		ConcreteMeditor meditor=new ConcreteMeditor();
		
		ConcreteColleague1 coll1=new ConcreteColleague1(meditor);
		ConcreteColleague2 coll2=new ConcreteColleague2(meditor);
		//中介者认识各个具体同事
		meditor.setColl1(coll1);
		meditor.setColl2(coll2);
		
		coll1.send("吃了吗");
		coll2.send("吃了");
		
		
	}

}

4、中介者模式的优缺点
1、中介者模式很容易在系统中应用,也容易在系统中误用,当系统出现了多对多的交互复杂的对象群时,不要急于使用中介者模式,首先反思在系统设计上是否合理。
优点:
2、Meditor的出现减少了各个Colleague之间的耦合,使得可以独立的改变和复用各个Colleague和Meditor。
3、把对象如何协作进行了抽象,将中介作为一个独立的概念并将其封装在一个对象中,这样关注的对象就从对象各自本身的行为转移到他们之间的交互上来,可以站在一个更宏观的角度看待系统。
缺点:
4、由于ConcreteMeditor控制集中化,就把交互的复杂性变成了中介者的复杂性,这就会使得中介者变得比任何一个ConcreteColleague更复杂。
使用:
5、中介者模式一般应用于一组对象以定义良好但是以复杂的方式进行通信的场合,以及想定制一个分布在多个类中的行为,而又不想定义太多子类的场合。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值