码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式之中介者模式

时间:2014-10-05 11:16:38      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   ar   java   sp   2014   c   on   

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

结构图:

bubuko.com,布布扣

示例代码:

public abstract class Mediator {

	public abstract void send(String message, Colleague colleague);
}

public class ConcreteMediator extends Mediator {

	ConcreteColleague1 colleague1;
	
	ConcreteColleague2 colleague2;
		
	public ConcreteColleague1 getColleague1() {
		return colleague1;
	}

	public void setColleague1(ConcreteColleague1 colleague1) {
		this.colleague1 = colleague1;
	}

	public ConcreteColleague2 getColleague2() {
		return colleague2;
	}

	public void setColleague2(ConcreteColleague2 colleague2) {
		this.colleague2 = colleague2;
	}

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

}

public abstract class Colleague {

	protected Mediator mediator;
	
	public Colleague(Mediator mediator) {
		
		this.mediator = mediator;
	}
}

public class ConcreteColleague1 extends Colleague {

	public ConcreteColleague1(Mediator mediator) {
		super(mediator);
		// TODO Auto-generated constructor stub
	}

	public void send(String message) {

		mediator.send(message, this);
	}

	public void notify(String message) {
		System.out.println("同事1得到消息:" + message);
	}
}

public class ConcreteColleague2 extends Colleague {

	public ConcreteColleague2(Mediator mediator) {
		super(mediator);
		// TODO Auto-generated constructor stub
	}

	public void send(String message) {
		
		mediator.send(message, this);
	}
	
	public void notify(String message) {
		System.out.println("同事2得到消息:" + message);
	}
}
客户端代码如下:

public class Client {
	
	public static void main(String[] args) {
		
		ConcreteMediator m = new ConcreteMediator();
		ConcreteColleague1 c1 = new ConcreteColleague1(m);
		ConcreteColleague2 c2 = new ConcreteColleague2(m);
		m.colleague1 = c1;
		m.colleague2 = c2;
		c1.send("吃饭没?");
		c2.send("没有呢,你打算请客?");
	}
}

输出结果:

同事2得到消息:吃饭没?

同事1得到消息:没有呢,你打算请客?


设计模式之中介者模式

标签:style   blog   http   ar   java   sp   2014   c   on   

原文地址:http://blog.csdn.net/tiandesheng111/article/details/39801077

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!