java设计模式--mediator 中介者模式

来源:互联网 发布:大闹天宫武器进阶数据 编辑:程序博客网 时间:2024/05/20 20:47
Mediator中介者模式,当多个对象彼此间都有联系的时候,我们就可以应用Mediator将对象间的多对多关系转换为一对多的关系,这样做,可以使各个对象间的耦合松散。统一管理对象间的交互。但也可能使得Mediator对象成为一个系统中的庞然大物,难以维护,以下是demo
public  class Colleague {       private String msg;       private static int number=1;       private final int id=number++;       private Mideator mi;       public  Colleague(Mideator mi)       {       this.mi=mi;       }public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;}public int getId() {return id;}    public void sendMsg(String msg){this.msg=msg;mi.action(this);}public  void sendMessage(){System.out.println("Colleague "+getId()+" sendMessage:"+getMsg());}public void getMessage(String msg){System.out.println("Colleague "+getId()+" getMessage():"+msg);}}
public abstract class Mideator {       public abstract void action(Colleague c);       public abstract void addColleague(Colleague c);}
public class ColleagueMideator extends Mideator{    private List<Colleague> CL=new ArrayList<Colleague>(0);@Overridepublic void action(Colleague c) {// TODO Auto-generated method stubString msg=c.getMsg();for(Colleague  colleague:CL){if(colleague.equals(c)){colleague.sendMessage();break;}}for(Colleague colleague:CL){if(colleague.equals(c)){continue;}colleague.getMessage(msg);}}@Overridepublic void addColleague(Colleague c) {// TODO Auto-generated method stubCL.add(c);}}
public class MideatorDemo1Test {       private static Mideator mi;         private static Colleague c1,c2,c3;       public static void main(String[] args)       {       mi=new ColleagueMideator();           c1=new Colleague(mi);           c2=new Colleague(mi);           c3=new Colleague(mi);                      mi.addColleague(c1);           mi.addColleague(c2);           mi.addColleague(c3);                      c1.sendMsg("hello ,the msg from c1");           c2.sendMsg("hello ,the msg from c2");           c3.sendMsg("hello ,the msg from c3");       }}
这个demo很简单,这要是构造中介者mideator来互相通信,最后通过遍历列表查询发送。



原创粉丝点击