标签:中介者模式 ima cli override else hide print getc sys
直接代码:
1 public abstract class Mediator { 2 public abstract void send(String message,Colleague coll); 3 }
1 public class ConcreteMediator extends Mediator { 2 private ConcreteColleague1 colleague1; 3 private ConcreteColleague2 colleague2; 4 @Override 5 public void send(String message, Colleague coll) { 6 if(coll==colleague1){ 7 colleague2.notify(message); 8 }else{ 9 colleague1.notify(message); 10 } 11 } 12 public ConcreteColleague1 getColleague1() { 13 return colleague1; 14 } 15 public void setColleague1(ConcreteColleague1 colleague1) { 16 this.colleague1 = colleague1; 17 } 18 public ConcreteColleague2 getColleague2() { 19 return colleague2; 20 } 21 public void setColleague2(ConcreteColleague2 colleague2) { 22 this.colleague2 = colleague2; 23 } 24 }
1 public abstract class Colleague { 2 protected Mediator mediator; 3 4 public Colleague(Mediator mediator) { 5 this.mediator = mediator; 6 } 7 }
1 public class ConcreteColleague1 extends Colleague { 2 3 public ConcreteColleague1(Mediator mediator) { 4 super(mediator); 5 } 6 7 public void sent(String message){ 8 mediator.send(message, this); 9 } 10 public void notify(String message){ 11 System.out.println("同事1得到消息"+message); 12 } 13 14 }
1 public class ConcreteColleague2 extends Colleague { 2 3 public ConcreteColleague2(Mediator mediator) { 4 super(mediator); 5 } 6 public void sent(String message){ 7 mediator.send(message, this); 8 } 9 public void notify(String message){ 10 System.out.println("同事2得到消息"+message); 11 } 12 13 }
1 public class MediatorTest { 2 public static void main(String[] args) { 3 ConcreteMediator me = new ConcreteMediator(); 4 5 ConcreteColleague1 c1 =new ConcreteColleague1(me); 6 ConcreteColleague2 c2 =new ConcreteColleague2(me); 7 8 me.setColleague1(c1); 9 me.setColleague2(c2); 10 11 c1.sent("吃饭了吗?"); 12 c2.sent("没有呢,你打算请客"); 13 } 14 }
同事2得到消息吃饭了吗?
同事1得到消息没有呢,你打算请客
标签:中介者模式 ima cli override else hide print getc sys
原文地址:https://www.cnblogs.com/cai170221/p/13398085.html