中介者模式(Mediator)定义:定义一个中介对象来封装一系列对象之间的交互,使原有对象之间的耦合松散,且可以独立地改变它们之间的交互。中介者模式又叫调停模式,它是迪米特法则的典型应用。
中介者模式的优点有:
1、降低了对象之间的耦合性,使得对象易于独立地被复用。
2、将对象间的一对多关联转变为一对一的关联,提高系统的灵活性,使得系统易于维护和扩展。
中介者:
1 public abstract class Mediator { 2 public abstract void register(Colleague colleague); 3 4 public abstract void remove(Colleague colleague); 5 6 public abstract void relay(Colleague colleague); 7 } 8 9 public class ConcreteMediator extends Mediator { 10 private List<Colleague> colleagues = new ArrayList<Colleague>(); 11 12 @Override 13 public void register(Colleague colleague) { 14 // TODO Auto-generated method stub 15 if (!colleagues.contains(colleague)) { 16 colleagues.add(colleague); 17 colleague.setMedium(this); 18 } 19 } 20 21 @Override 22 public void remove(Colleague colleague) { 23 // TODO Auto-generated method stub 24 if (colleagues.contains(colleague)) { 25 colleagues.remove(colleague); 26 } 27 } 28 29 @Override 30 public void relay(Colleague colleague) { 31 // TODO Auto-generated method stub 32 for (Colleague cl : colleagues) { 33 if (!cl.equals(colleague)) { 34 cl.setMsg(colleague.getMsg()); 35 cl.receive(); 36 } 37 } 38 } 39 }
同事类:
1 public abstract class Colleague { 2 protected Mediator mediator; 3 4 private String Msg; 5 6 public String getMsg() { 7 return Msg; 8 } 9 10 public void setMsg(String msg) { 11 Msg = msg; 12 } 13 14 public void setMedium(Mediator mediator) { 15 this.mediator = mediator; 16 } 17 18 public abstract void receive(); 19 20 public abstract void send(); 21 } 22 23 public class ConcreteColleagueA extends Colleague { 24 @Override 25 public void receive() { 26 System.out.println("A收到请求<-" + getMsg()); 27 } 28 29 @Override 30 public void send() { 31 System.out.println("A发出请求->" + getMsg()); 32 mediator.relay(this); // 请中介者转发 33 } 34 } 35 36 public class ConcreteColleagueB extends Colleague { 37 @Override 38 public void receive() { 39 System.out.println("B收到请求<-" + getMsg()); 40 } 41 42 @Override 43 public void send() { 44 System.out.println("B发出请求->" + getMsg()); 45 mediator.relay(this); // 请中介者转发 46 } 47 } 48 49 public class ConcreteColleagueC extends Colleague { 50 @Override 51 public void receive() { 52 System.out.println("C收到请求<-" + getMsg()); 53 54 } 55 56 @Override 57 public void send() { 58 System.out.println("C发出请求->" + getMsg()); 59 mediator.relay(this); // 请中介者转发 60 } 61 }
调用方式:
1 public class Client { 2 /* 3 * 定义一个中介对象来封装一系列对象之间的交互, 使原有对象之间的耦合松散,且可以独立地改变它们之间的交互。 4 */ 5 public static void main(String[] args) { 6 // 声明中介者对象 7 Mediator md = new ConcreteMediator(); 8 9 // 在中介者的用户列表中进行登记 10 Colleague c1 = new ConcreteColleagueA(); 11 Colleague c2 = new ConcreteColleagueB(); 12 Colleague c3 = new ConcreteColleagueC(); 13 14 md.register(c1); 15 md.register(c2); 16 md.register(c3); 17 18 // 用户A发送消息 19 c1.setMsg("B你退出吧!"); 20 c1.send(); 21 22 //用户B退出 23 md.remove(c2); 24 25 System.out.println("-------------------"); 26 // 用户C发送消息 27 c3.setMsg("B你还在吗?"); 28 c3.send(); 29 } 30 }
执行结果:
中介者模式是星形网络拓扑结构的体现。