您现在的位置是:网站首页> 设计模式 设计模式

中介者模式

夜雨 2015-10-30 17:39 设计模式,中介者模式 1378人已围观

简介中介者模式

// 抽象中介者
public abstract class Mediator {
	public abstract void Send(String message,Colleague colleague);

}


// 具体中介者
public class ConcreteMediator extends Mediator {
	
	private ConcreteColleagueA colleagueA;
	private ConcreteColleagueB colleagueB;

	@Override
	public void Send(String message, Colleague colleague) {
		// TODO Auto-generated method stub
		
		if(colleague==colleagueA){
			colleagueA.Notify(message);
		}else{
			colleagueB.Notify(message);
		}

	}
	
	// 设定同事A
	public void setColleagueA(ConcreteColleagueA colleagueA){
		this.colleagueA=colleagueA;
	}
	
	// 设定同事B
	public void setColleagueB(ConcreteColleagueB colleagueB){
		this.colleagueB=colleagueB;
	}

}


// 抽象同事类
public abstract class Colleague {
	protected Mediator mediator;
	
	// 构造函数
	public Colleague(Mediator mediator){
		this.mediator=mediator;
	}

}


// 具体同事A
public class ConcreteColleagueA extends Colleague {

	public ConcreteColleagueA(Mediator mediator) {
		super(mediator);
		// TODO Auto-generated constructor stub
	}
	
	// 转发信息给同事A
	public void Send(String message){
		mediator.Send(message, this);
	}
	
	// 收信通知
	public void Notify(String message){
		System.out.println("Colleague A got a message:"+message);
	}

}


// 具体同事B
public class ConcreteColleagueB extends Colleague {

	public ConcreteColleagueB(Mediator mediator) {
		super(mediator);
		// TODO Auto-generated constructor stub
	}
	
	// 转发信息给同事B
	public void Send(String message){
		mediator.Send(message, this);
	}
	
	// 收信通知
	public void Notify(String message){
		System.out.println("Colleague B got a message:"+message);
	}

}


public class Test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		ConcreteMediator concreteMediator=new ConcreteMediator();
		
		ConcreteColleagueA CA=new ConcreteColleagueA(concreteMediator);
		ConcreteColleagueB CB=new ConcreteColleagueB(concreteMediator);
		
		concreteMediator.setColleagueA(CA);
		concreteMediator.setColleagueB(CB);
		
		CA.Send("Hello,I am A!");
		CB.Send("I am B! How do you do!");

	}

}

很赞哦!(504)

上一篇: 命令模式

下一篇:备忘录模式

文章评论

夜雨

夜雨(共34篇文章)

弃我去者,昨日之日不可留
乱我心者,今日之日多烦忧
长风万里送秋雁,对此可以酣高楼
蓬莱文章建安骨,中间小谢又清发
俱怀逸兴壮思飞,欲上青天览明月
抽刀断水水更流,举杯消愁愁更愁
人生在世不称意,明朝散发弄扁舟