仲裁者模式_只有一个老大(系统内的所有人都要上报行为并接受老大分配的任务)
/**
* 仲裁者父类
* @author maikec
* @date 2019/5/14
*/
public abstract class AbstractMediator {
protected final Map<Integer, AbstractColleague> colleagueMap;
public AbstractMediator(){
colleagueMap = Collections.synchronizedMap( new HashMap() );
}
/**
* 注入成员
* @param id 成员id
* @param colleague 成员
*/
public final void register(Integer id,AbstractColleague colleague){
colleagueMap.put(id,colleague);
}
/**
* 下发任务
* @param id 成员id
* @param msg 消息
*/
public abstract void operation(Integer id, String msg);
}
/**
* 成员父类
* @author maikec
* @date 2019/5/14
*/
public abstract class AbstractColleague {
protected AbstractMediator mediator;
public AbstractColleague(){}
public AbstractColleague(AbstractMediator mediator){
this.mediator = mediator;
}
/**
* 请求上报给仲裁者
* @param toId 消息接收者id
* @param msg
*/
public abstract void sendMsg(Integer toId, String msg);
public void receiveMsg(String msg){
System.out.println( this+" receive "+msg );
}
}
/**
* @author maikec
* @date 2019/5/14
*/
public class ColleagueMediator extends AbstractMediator {
@Override
public void operation(Integer id, String msg) {
if (colleagueMap.isEmpty()){
throw new IllegalStateException("需要注入成员");
}
if (colleagueMap.containsKey( id )){
colleagueMap.get( id ).receiveMsg( msg );
}else{
throw new IllegalStateException( "未包含该成员:"+id );
}
}
}
/**
* @author maikec
* @date 2019/5/14
*/
public class ColleagueA extends AbstractColleague {
public ColleagueA(){super();}
public ColleagueA(AbstractMediator mediator){
super(mediator);
}
@Override
public void sendMsg(Integer toId, String msg) {
mediator.operation( toId, msg );
}
}
/**
* @author maikec
* @date 2019/5/14
*/
public class ColleagueB extends AbstractColleague {
public ColleagueB(){super();}
public ColleagueB(AbstractMediator mediator){
super(mediator);
}
@Override
public void sendMsg(Integer toId, String msg) {
mediator.operation( toId, msg );
}
}
/**
* @author maikec
* @date 2019/5/14
*/
public class MediatorDemo {
public static void main(String[] args) {
//创建仲裁者
AbstractMediator colleagueMediator = new ColleagueMediator();
//创建成员并设置仲裁者
AbstractColleague colleagueA = new ColleagueA( colleagueMediator );
AbstractColleague colleagueB = new ColleagueB( colleagueMediator );
//注入成员
colleagueMediator.register( 1,colleagueA );
colleagueMediator.register( 2,colleagueB );
colleagueA.sendMsg( 2,"Hi,I am A" );
colleagueB.sendMsg( 1,"Hi,I am B" );
}
}
复制代码
附录
github.com/maikec/patt… 个人GitHub设计模式案例
声明
引用该文档请注明出处