参考:https://blog.csdn.net/weixin_48052161/article/details/117048990
中介者模式:比如为服务的注册中心就为一个中介;
主要是接口加上集合的使用,类之间的关系为聚合的关系;
抽象中介类:
package com.example.dtest.design23.mediator;
public interface Mediator {
void register(Colleague colleague);//注册
void relay(Colleague colleague,String msg);//转发
}
实现中介具体类:将同事类以list集合聚合,以注册方法添加!
package com.example.dtest.design23.mediator;
import java.util.ArrayList;
import java.util.List;
public class ConcreteMediator implements Mediator{
//创建一共list来管理同事类
private List<Colleague> list = new ArrayList<>();
@Override
public void register(Colleague colleague) {
//list是否包含colleague
if(!list.contains(colleague)){
//添加并设置中介类
list.add(colleague);
colleague.setMedium(this);
}
}
@Override
public void relay(Colleague colleague, String msg) {
//遍历客户
for(Colleague cl:list){
//如果不为发送者,则进行接收
if(!cl.equals(colleague)){
cl.recive(msg);
}
}
}
}
同事抽象类:
package com.example.dtest.design23.mediator;
public interface Colleague {
void setMedium(Mediator mediator);//注册
void recive(String msg);//接收
void send(String msg);//发送
}
同事抽象类1、2:
package com.example.dtest.design23.mediator;
public class ConcreteColleague01 implements Colleague{
private Mediator mediator;
@Override
public void setMedium(Mediator mediator) {
this.mediator = mediator;
}
@Override
public void recive(String msg) {
System.out.println("具体同事类1收到请求:"+msg);
}
@Override
public void send(String msg) {
System.out.println("具体同事类1发出请求:"+msg);
mediator.relay(this,msg);
}
}
package com.example.dtest.design23.mediator;
public class ConcreteColleague02 implements Colleague{
private Mediator mediator;
@Override
public void setMedium(Mediator mediator) {
this.mediator = mediator;
}
@Override
public void recive(String msg) {
System.out.println("具体同事类2收到请求:"+msg);
}
@Override
public void send(String msg) {
System.out.println("具体同事类2发出请求:"+msg);
mediator.relay(this,msg);
}
}
测试类:
package com.example.dtest.design23.mediator;
public class MediatorTest {
public static void main(String[] args) {
//创建中介类
Mediator mediator = new ConcreteMediator();
//创建客户
Colleague colleague1 = new ConcreteColleague01();
Colleague colleague2 = new ConcreteColleague02();
//注册
mediator.register(colleague1);
mediator.register(colleague2);
colleague1.send("您好");
System.out.println("-------------------------");
colleague2.send("我很好! ");
}
}
中介模式:内涵了策略模式!