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.结果