一、定义

用一个中介对象封装了一系列对象的交互行为。中介者使各个对象不需要显式的相互引用,从而实现低耦合,而且可以独立的改变它们之间的交互。

二、类图表示

中介者模式

三、实现

1、Colleague

package pattern.behavioral.mediator;

public abstract class Colleague {

	protected Mediator mediator;
	protected int money;
	
	public Colleague(Mediator mediator, int money) {
		this.mediator = mediator;
		this.money = money;
		System.out.println(String.format("%s's initial amount: %s ", this.getClass().getSimpleName(), money));
	}
	
	public int getMoney() {
		return money;
	}

	public void loan(int money){
		this.money -= money;
	}
	
	public void gain(int money){
		this.money += money;
	}
}


package pattern.behavioral.mediator;

public class ConcreteColleagueA extends Colleague {

	public ConcreteColleagueA(Mediator mediator, int money) {
		super(mediator, money);
	}

}


package pattern.behavioral.mediator;

public class ConcreteColleagueB extends Colleague {

	public ConcreteColleagueB(Mediator mediator, int money) {
		super(mediator, money);
	}

}

2、Mediator

package pattern.behavioral.mediator;

public abstract class Mediator {

	public abstract void borrow(Colleague who, int money);
}


package pattern.behavioral.mediator;

public class ConcreteMediator extends Mediator {

	private Colleague colleagueA;
	private Colleague colleagueB;
	
	public void setColleagueA(Colleague ca) {
		this.colleagueA = ca;
	}

	public void setColleagueB(Colleague cb) {
		this.colleagueB = cb;
	}

	@Override
	public void borrow(Colleague who, int money) {
		String fromWhom = ConcreteColleagueB.class.getSimpleName();
		if(who instanceof ConcreteColleagueA){
			colleagueB.loan(money);
		}else{
			fromWhom = ConcreteColleagueA.class.getSimpleName();
			colleagueA.loan(money);
		}
		who.gain(money);
		System.out.println(String.format("%s borrow %s$ from %s", who.getClass().getSimpleName(), money, fromWhom));
	}

}

四、使用

package pattern.behavioral.mediator;

public class Client {

	public static void main(String[] args) {
		ConcreteMediator mediator = new ConcreteMediator();
		Colleague ca = new ConcreteColleagueA(mediator, 500);
		Colleague cb = new ConcreteColleagueB(mediator, 600);
		
		System.out.println();
		
		mediator.setColleagueA(ca);
		mediator.setColleagueB(cb);
		mediator.borrow(ca, 100);
		mediator.borrow(cb, 500);
		
		System.out.println();
		
		System.out.println("ConcreteColleagueA's money: " + ca.getMoney());
		System.out.println("ConcreteColleagueB's money: " + cb.getMoney());
	}
}
  • 程序输出:
ConcreteColleagueA's initial amount: 500 
ConcreteColleagueB's initial amount: 600 

ConcreteColleagueA borrow 100$ from ConcreteColleagueB
ConcreteColleagueB borrow 500$ from ConcreteColleagueA

ConcreteColleagueA's money: 100
ConcreteColleagueB's money: 1000

五、适用场合

  • 当一组对象以定义良好但是复杂的方式进行通信,产生相互依赖的关系,结构混乱且难以理解时

  • 想通过一个中间的类来封装多个类中的行为,而又不想生成太多子类时