中介者模式

Posted cai170221

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了中介者模式相关的知识,希望对你有一定的参考价值。

技术图片

 

 直接代码:

技术图片
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得到消息没有呢,你打算请客
测试打印

 

以上是关于中介者模式的主要内容,如果未能解决你的问题,请参考以下文章

(十九)中介者模式-代码实现

设计模式之中介者模式

20160227.CCPP体系详解(0037天)

设计模式----中介者模式及简单总结(2018/10/30)

中介者模式分析结构图及基本代码

设计模式之中介者模式