一 概要
1.1 行为型模式
- 特别关注对象之间的通信。描述类或对象之间怎样相互协作共同完成单个对象都无法单独完成的任务,以及怎样分配职责。
1.2 定义
- 定义一个中介对象来封装一系列对象之间的交互,使原有对象之间的耦合松散,且可以独立地改变它们之间的交互。中介者模式又叫调停模
- 型应用。
二 UML类图

三 例子
class Program
{
static void Main(string[] args)
{
MediatorA mediator = new MediatorA();
Colleague colleagueA = new ColleagueA(mediator);
Colleague colleagueB = new ColleagueB(mediator);
mediator.ColleagueA = colleagueA;
mediator.ColleagueB = colleagueB;
colleagueA.Send("haha");
}
}
public interface Mediator
{
void Send(object message, Colleague colleague);
}
public interface Colleague
{
void Notify(object message);
void Send(object message);
}
public class MediatorA : Mediator
{
public Colleague ColleagueA { get; set; }
public Colleague ColleagueB { get; set; }
public void Send(object message, Colleague colleague)
{
if (colleague == ColleagueB)
{
ColleagueA.Notify(message);
}
else if (colleague == ColleagueA)
{
ColleagueB.Notify(message);
}
}
}
public class ColleagueA : Colleague
{
private Mediator mediator;
public ColleagueA(Mediator mediator)
{
this.mediator = mediator;
}
public void Send(object message)
{
if (this.mediator != null)
{
this.mediator.Send(message, this);
}
}
public void Notify(object message)
{
}
}
public class ColleagueB : Colleague
{
private Mediator mediator;
public ColleagueB(Mediator mediator)
{
this.mediator = mediator;
}
public void Send(object message)
{
if (this.mediator != null)
{
this.mediator.Send(message, this);
}
}
public void Notify(object message)
{
}
}
四 优缺点
4.1 优点
- 减少了各个Colleague的耦合, 使得可以独立的更变和复用各个Colleague和Mediator。
4.2 缺点
- Mediator会变得更加复杂, 因为统一处理了各个Colleague的交互,与各个colleague高度耦合。
五 使用场景
- 当对象之间存在复杂的网状结构关系而导致依赖关系混乱且难以复用时。
- 当想创建一个运行于多个类之间的对象,又不想生成新的子类时。