首页 > 代码库 > 设计模式之中介者模式

设计模式之中介者模式

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

结构图:


示例代码:

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得到消息:没有呢,你打算请客?


设计模式之中介者模式