0%

设计模式-中介者模式

用来降低多个对象和类之间的通信复杂性。这种模式提供了一个中介类,该类通常处理不同类之间的通信,并支持松耦合,使代码易于维护
用一个中介对象来封装一系列的对象交互,中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互
对象与对象之间存在大量的关联关系,这样势必会导致系统的结构变得很复杂,同时若一个对象发生改变,我们也需要跟踪与之相关联的对象,同时做出相应的处理

中介者模式

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
//Mediator 抽象中介者
abstract class Mediator
{
public abstract void Send(string message, Colleague colleague);
}
//Colleague 抽象同事类
abstract class Colleague
{
protected Mediator mediator;
public Colleague(Mediator mediator)
{
this.mediator = mediator;
}
}
class ConcreateMediator : Mediator
{
private ConcreateColleague1 colleague1;
private ConcreateColleague2 colleague2;
public ConcreateColleague1 Colleague1
{
set{colleague1 = value;}
}
public ConcreateColleague2 Colleague2
{
set{colleague2 = value;}
}
public override void Send(string message, Colleague colleague)
{
if(colleague == colleague1)
colleague2.Notify(message)
else
colleague1.Notify(message);
}
}
class ConcreateColleague1 : Colleague
{
public ConcreateColleague1(Mediator mediator) : base(mediator)
{}
public void Send(string message)
{
mediator.Send(message, this);
}
public void Notify(string message)
{
Console.WriteLine("Colleague 1 Recv " + message);
}
}
class ConcreateColleague2 : Colleague
{
public ConcreateColleague2(Mediator mediator) : base(mediator)
{}
public void Send(string message)
{
mediator.Send(message, this);
}
public void Notify(string message)
{
Console.WriteLine("Colleague 2 Recv " + message);
}
}
//Client
ConcreateMediator m = new ConcreateMediator();//创建中介
ConcreateColleague1 c1 = new ConcreateColleague1(m);//让同事都认识中介
ConcreateColleague2 c2 = new ConcreateColleague2(m);

m.colleague1 = c1;//让中介认识同事
m.colleague2 = c2;

c1.Send("你瞅啥");
c2.Send("瞅你咋地");