中介者设计模式--练习

1.UML



2.代码

Mediator

abstract  class Mediator 
{
	public abstract  void SendMessage(String message, Colleague colleague);
}

Colleague

abstract class Colleague
{
	protected Mediator mediator; //中介

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

ColleagueColleagueA

class ConcreteColleagueA extends Colleague
{
	public ConcreteColleagueA(Mediator mediator)
	{
		super(mediator);
	}

	public void Send(String message)
	{
		mediator.SendMessage(message, this);
	}

	public void Notify(String message)
	{
		System.out.println("同事A收到消息: "+message);
	}
}
ColleagueColleagueB

class ConcreteColleagueB extends Colleague
{
	public ConcreteColleagueB(Mediator mediator)
	{
		super(mediator);
	}

	public void Send(String message)
	{
		mediator.SendMessage(message, this);
	}

	public void Notify(String message)
	{
		System.out.println("同事B收到消息: "+message);
	}
}
class ConcreteMediator extends Mediator
{
	private  ConcreteColleagueA A;  //同事A
	private  ConcreteColleagueB B;  //同事B

	public void SendMessage(String message, Colleague colleague)
	{
		if (colleague.equals(A)) //同事A发消息
		{
			B.Notify(message);   //同事B接收消息
		}
		else
		{
			A.Notify(message);
		}
	}
	
	
    public void setConcreteColleagueA(ConcreteColleagueA A)
    {
    	this.A = A;
    }

    public void setConcreteColleagueB(ConcreteColleagueB B)
    {
    	this.B = B;
    }
}
Test

public class Test
{
	public static void main(String[] args) 
	{
		//中介
		ConcreteMediator  m = new ConcreteMediator();
        //同事
		ConcreteColleagueA A = new ConcreteColleagueA(m);
		ConcreteColleagueB B = new ConcreteColleagueB(m);
		//将同事添加到中介中,组网
		m.setConcreteColleagueA(A);
		m.setConcreteColleagueB(B);

		//同事间聊天
		A.Send("吃饭没");
		B.Send("还没吃,要不请我吃饭");

		

	}
}

3.结果






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值