读《研磨设计模式》-代码笔记-中介者模式-Mediator

声明:
本文只为方便我个人查阅和理解,详细的分析以及源代码请移步 原作者的博客http://chjavach.iteye.com/




/*
 * 中介者模式(Mediator):用一个中介对象来封装一系列的对象交互。
 * 中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
 * 
 * 在我看来,Mediator模式是把多个对象(Colleague)之间的交互集中到一个类(Mediator),由Mediator统一控制
 * Colleague之间就不再直接联系了(就解耦了),而是要通过Mediator才能间接联系上
 * 
 * 所以实现思路也就清晰了:
 * Colleague要能联系上Mediator,反过来也一样,Mediator和Colleague是互相依赖的,互相“持有”的
 * 
 * 中介者模式的缺点也很明显:Mediator可能会非常庞大和复杂
 * 
 * 以下实现是用“类组合”的方式来做
 * 若要简化:
 * 1、将Mediator实现成一个单例,那当Colleague需要用到Mediator时,直接getInstance
 * 2、当Mediator需要用到Colleague时,a.直接当成方法的参数传递过来 b.针对不同的Colleague定义不同的方法 等等
 */

interface Mediator {
	void change(Colleague colleague);
}

abstract class Colleague {
	
	private Mediator mediator;

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

}

class ColleagueImplA extends Colleague {
	
	public ColleagueImplA(Mediator mediator) {
		super(mediator);
	}
	
	public void doSomethingA() {
		getMediator().change(this);
	}
	
}

class ColleagueImplB extends Colleague {
	
	public ColleagueImplB(Mediator mediator) {
		super(mediator);
	}
	
	public void doSomethingB() {
		getMediator().change(this);
	}
	
}

class MediatorImpl implements Mediator {

    //这里也可以用Map/List来管理Colleague,提供add、 delete等方法
	private ColleagueImplA colleagueA;
	
	private ColleagueImplB colleagueB;
	
	public void setColleagueA(ColleagueImplA colleagueA) {
		this.colleagueA = colleagueA;
	}
	
	public void setColleagueB(ColleagueImplB colleagueB) {
		this.colleagueB = colleagueB;
	}
	
	//协调Colleague之间的交互,如果Colleague非常多,或者业务逻辑非常复杂的话,这个方法会非常庞大
	//这个方法也可以灵活改变,例如传递更多的参数:change(Colleague c, String demand)等等
	public void change(Colleague colleague) {
		if (colleague == colleagueA) {
			System.out.println("colleagueA changed,now colleagueB can do something to react.");
		}
		if (colleague == colleagueB) {
			System.out.println("colleagueB changed,now colleagueA can do something to react.");
		}
	}
	
}


public class MediatorPattern {
	public static void main(String[] args) {
		MediatorImpl mediator = new MediatorImpl();
		ColleagueImplA colleagueA = new ColleagueImplA(mediator);
		ColleagueImplB colleagueB = new ColleagueImplB(mediator);
		mediator.setColleagueA(colleagueA);
		mediator.setColleagueB(colleagueB);
		colleagueA.doSomethingA();
	}

}

你可能感兴趣的:(java,设计模式)