中介者模式

文檔查閱說明:

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("還沒,你請?");
		
	}
}

 

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