前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >[设计模式]之八:中介者模式

[设计模式]之八:中介者模式

作者头像
wOw
发布2018-09-18 15:17:20
3900
发布2018-09-18 15:17:20
举报

定义

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

UML

示例代码

// 比如两个同事分别熟悉CTS和SElinux的问题,现在要找他们协助,就需要找PM协调
// 同事之间不一定都认识,但PM肯定认识。所以PM作为中介者
interface Mediator {
	public void send(String msg, Colleague colleague);
}
// PM认识所有同事,所以会持有同事们的实例,然后管理同事
public class ConcreteMediator implements Mediator {

	private ConcreteColleague1 tom;
	private ConcreteColleague2 jerry;

	public void setTom(ConcreteColleague1 tom) {
		this.tom = tom;
	}

	public void setJerry(ConcreteColleague2 jerry) {
		this.jerry = jerry;
	}
	
	@Override
	public void send(String msg, Colleague colleague) {
		// TODO Auto-generated method stub
		if (colleague.getClass().equals(tom.getClass())) {
			jerry.notify(msg);
		} else {
			tom.notify(msg);
		}
	}

}
//同事只认识PM  由PM转发消息
abstract class Colleague {
	protected Mediator mediator;
	
	public Colleague(Mediator mediator) {
		this.mediator = mediator;
	}
}
public class ConcreteColleague1 extends Colleague {

	public ConcreteColleague1(Mediator mediator) {
		super(mediator);
	}
	
	public void send(String msg) {
		mediator.send(msg, this);
	}
	
	public void notify(String msg) {
		System.out.println("Hi Tom: " + msg);
	}
}
public class ConcreteColleague2 extends Colleague {

	public ConcreteColleague2(Mediator mediator) {
		super(mediator);
	}
	
	public void send(String msg) {
		mediator.send(msg, this);
	}
	
	public void notify(String msg) {
		System.out.println("Hi Jerry: " + msg);
	}

}
//客户代码
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ConcreteMediator mediator = new ConcreteMediator();
		
		ConcreteColleague1 tom = new ConcreteColleague1(mediator);
		ConcreteColleague2 jerry = new ConcreteColleague2(mediator);
		
		mediator.setTom(tom);
		mediator.setJerry(jerry);
		
		tom.send("Could you do the CTS job?");
		jerry.send("Could you do the SElinux job?");
	}
//输出
Hi Jerry: Could you do the CTS job?
Hi Tom: Could you do the SElinux job?

评价

当系统出现多对多交互复杂的对象群时,不要急着使用中介者模式,而要先反思你的系统在设计上是不是合理。

优点: 减少各个Colleague之间的耦合,使得可以独立地改变和复用各个Colleague类和Mediator 缺点: Mediator实现过于复杂

计算器就是中介者模式的实现,所有按键以及屏幕互相不了解,中介者处理按键结果给屏幕显示

适用于一组对象用定义良好但是复杂的方式进行通信的场合

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-03-30,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 定义
  • UML
  • 示例代码
  • 评价
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档