中介者模式

文档查阅说明:

Tongkey

yiibai

runoob

大话设计模式

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

使用场景:

● 系统中对象之间存在比较复杂的引用关系,导致它们之间的依赖关系结构混乱而且难以复用该对象;

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

● 中介者模式适用于多个对象之间紧密耦合的情况,紧密耦合的标准是:在类图中出现了蜘蛛网状结构,即每个类都与其他的类有直接的联系

public abstract class Madiator {
	public abstract void send(String message, Colleague colleague);
}
public abstract class Colleague {
	private Madiator madiator;
	
	public Colleague(Madiator madiator) {
		super();
		this.madiator = madiator;
	}

	public Madiator getMadiator() {
		return madiator;
	}

	public void setMadiator(Madiator madiator) {
		this.madiator = madiator;
	}
	
	public abstract void send(String message);
	
	public abstract void notify(String message);
}
public class ConCreateColleagueA extends Colleague {

	public ConCreateColleagueA(Madiator madiator) {
		super(madiator);
	}

	@Override
	public void send(String message) {
		this.getMadiator().send(message, this);
	}

	@Override
	public void notify(String message) {
		System.out.println("同事A收到消息:"+message);
	}
	
}
public class ConCreateColleagueB extends Colleague {

	public ConCreateColleagueB(Madiator madiator) {
		super(madiator);
	}

	@Override
	public void send(String message) {
		this.getMadiator().send(message, this);
	}

	@Override
	public void notify(String message) {
		System.out.println("同事B收到消息:"+message);
	}
	
}
public class ConCreateMadiator extends Madiator {

	private ConCreateColleagueA colleagueA;
	private ConCreateColleagueB colleagueB;
	
	public ConCreateColleagueA getColleagueA() {
		return colleagueA;
	}

	public void setColleagueA(ConCreateColleagueA colleagueA) {
		this.colleagueA = colleagueA;
	}
	
	public ConCreateColleagueB getColleagueB() {
		return colleagueB;
	}

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

	@Override
	public void send(String message, Colleague colleague) {
		if(colleague == colleagueA) {
			colleagueB.notify(message);
		}else {
			colleagueA.notify(message);
		}
	}

}
public class Test {
	public static void main(String[] args) {
		ConCreateMadiator madiator = new ConCreateMadiator();
		
		ConCreateColleagueA colleagueA = new ConCreateColleagueA(madiator);
		ConCreateColleagueB colleagueB = new ConCreateColleagueB(madiator);
		
		madiator.setColleagueA(colleagueA);
		madiator.setColleagueB(colleagueB);
		
		colleagueA.send("吃饭了没!");
		colleagueB.send("还没,你请?");
		
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章