UML
抽象中介者类 代替某个对象去做某些事情
public abstract class Mediator {
public abstract void send(String message, Colleague colleague);
}
具体的中介者类
public class ConcreteMediator extends Mediator {
private ColleagueImpl1 colleagueImpl1;
private ColleagueImpl2 colleagueImpl2;
public void setColleagueImpl1(ColleagueImpl1 colleagueImpl1) {
this.colleagueImpl1 = colleagueImpl1;
}
public void setColleagueImpl2(ColleagueImpl2 colleagueImpl2) {
this.colleagueImpl2 = colleagueImpl2;
}
@Override
public void send(String message, Colleague colleague) {
if (colleague instanceof ColleagueImpl1) {
colleagueImpl2.receiveMessage(message);
} else if (colleague instanceof ColleagueImpl2) {
colleagueImpl1.receiveMessage(message);
}
}
}
抽象同事类
public abstract class Colleague {
protected Mediator mediator;
public Colleague(Mediator mediator) {
this.mediator = mediator;
}
public abstract void send(String message);
public abstract void receiveMessage(String message);
}
具体的同事对象1
public class ColleagueImpl1 extends Colleague {
public ColleagueImpl1(Mediator mediator) {
super(mediator);
}
@Override
public void send(String message) {
mediator.send(message, this);
}
@Override
public void receiveMessage(String message) {
System.out.println("具体的同事对象1接收到消息--->" + message);
}
}
具体的同事对象2
public class ColleagueImpl2 extends Colleague {
public ColleagueImpl2(Mediator mediator) {
super(mediator);
}
@Override
public void send(String message) {
mediator.send(message, this);
}
@Override
public void receiveMessage(String message) {
System.out.println("具体的同事对象2接收到消息--->" + message);
}
}
测试类
public class Main {
public static void main(String[] args) {
ConcreteMediator concreteMediator = new ConcreteMediator();
ColleagueImpl1 colleagueImpl1 = new ColleagueImpl1(concreteMediator);
ColleagueImpl2 colleagueImpl2 = new ColleagueImpl2(concreteMediator);
concreteMediator.setColleagueImpl1(colleagueImpl1);
concreteMediator.setColleagueImpl2(colleagueImpl2);
colleagueImpl1.send("你好,我是同事1~");
colleagueImpl2.send("你也好啊,我是同事2~");
}
}
运行结果
具体的同事对象2接收到消息--->你好,我是同事1~
具体的同事对象1接收到消息--->你也好啊,我是同事2~