服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服务器之家 - 编程语言 - JAVA教程 - Java设计模式之中介者模式(Mediator Pattern)简介

Java设计模式之中介者模式(Mediator Pattern)简介

2019-11-25 14:30shichen2014 JAVA教程

这篇文章主要介绍了Java设计模式之中介者模式(Mediator Pattern),需要的朋友可以参考下

Java设计模式的中介者模式是行为模式之一。定义一个中介对象来封装系列对象之间的交互。中介者使各个对象不需要显式地相互引用,从而使其耦合性松散,并且可以独立地改变他们之间的交互。

如下图所示:

Java设计模式之中介者模式(Mediator Pattern)简介

生产者、消费者、代理商之间的中介模式实例:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
public abstract class PersonColleague
{
  protected Mediator mediator;
 
  public Mediator getMediator()
  {
    return mediator;
  }
 
  public void setMediator(final Mediator mediator)
  {
    this.mediator = mediator;
  }
 
  protected abstract void message(String context);
 
}
 
public class Mediator
{
  private PersonColleague consumer = null;
  private ProducerColleague producer = null;
 
  public ProducerColleague getProducer()
  {
    return producer;
  }
 
  public void setProducer(final ProducerColleague producer)
  {
    this.producer = producer;
  }
 
  public PersonColleague getConsumer()
  {
    return consumer;
  }
 
  public void setConsumer(final PersonColleague consumer)
  {
    this.consumer = consumer;
  }
 
  public Mediator()
  {
  }
 
  public synchronized void message(final String context)
  {
    if (consumer != null)
    {
      System.out.println(context);
    }
    else if (producer != null)
    {
      System.out.println(context);
    }
  }
}
 
public class ConsumerColleague extends PersonColleague
{
  public ConsumerColleague(final Mediator mediator)
  {
    this.mediator = mediator;
  }
 
  @Override
  protected void message(final String context)
  {
    this.mediator.setConsumer(this);
    this.mediator.message("hello! i am a consumer");
  }
}
 
public class ProducerColleague extends PersonColleague
{
  public ProducerColleague(final Mediator mediator)
  {
    this.mediator = mediator;
  }
 
  @Override
  protected void message(final String context)
  {
    this.mediator.setProducer(this);
    this.mediator.message(context);
  }
}
 
public class Client
{
  public static void main(final String[] args)
  {
    final Mediator mediator = new Mediator();
    final PersonColleague person = new ConsumerColleague(mediator);
    final PersonColleague person1 = new ProducerColleague(mediator);
 
    person.message("I am a consumer");
    person1.message("I am a producer");
  }
}

运行结果:

?
1
2
hello! i am a consumer
I am a producer

 

延伸 · 阅读

精彩推荐