码迷,mamicode.com
首页 > 其他好文 > 详细

中介者模式

时间:2020-07-29 17:31:24      阅读:69      评论:0      收藏:0      [点我收藏+]

标签:中介者模式   ima   cli   override   else   hide   print   getc   sys   

技术图片

 

 直接代码:

技术图片
1 public abstract class Mediator {
2     public abstract void send(String message,Colleague coll);
3 }
Mediator
技术图片
 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 }
ConcreteMediator
技术图片
1 public abstract class Colleague {
2     protected Mediator mediator;
3 
4     public Colleague(Mediator mediator) {
5         this.mediator = mediator;
6     }
7 }
Colleague
技术图片
 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 }
ConcreteColleague1
技术图片
 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 }
ConcreteColleague2
技术图片
 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 }
test
技术图片
同事2得到消息吃饭了吗?
同事1得到消息没有呢,你打算请客
测试打印

 

中介者模式

标签:中介者模式   ima   cli   override   else   hide   print   getc   sys   

原文地址:https://www.cnblogs.com/cai170221/p/13398085.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!