# 中介者模式
属于行为型模式。
用一个中介对象来封装一系列的对象交互,中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
适用性:
- 一组对象以定义良好但是复杂的方式进行通信,产生的相互依赖关系结构混乱且难以理解。
- 一个对象引用其他很多对象并且直接与这些对象通信,导致难以复用该对象。
- 想通过一个中间类来封装多个类中的行为,而又不想生成太多的子类。
- 中介者模式将对象与对象之间交互的复杂性转变为了中介者的复杂性
- 中介者模式很容易在系统中应用,也很容易在系统中误用。当系统出现了多对多交互复杂的对象群时,不要急于使用中介者模式,而是要先反思系统在设计上是否合理。
网络聊天室是一个很好的例子。
# 类图

# 代码
# 需要相互通信的类
namespace BehavioralPatterns_MediatorPattern | |
{ | |
/// <summary> | |
/// 玩家 | |
/// </summary> | |
public abstract class Player | |
{ | |
/// <summary> | |
/// 中介者 | |
/// </summary> | |
protected Mediator MainMediator; | |
public Player(Mediator mainMediator) | |
{ | |
MainMediator = mainMediator; | |
} | |
/// <summary> | |
/// 发送消息 | |
/// </summary> | |
/// <param name="target"> 目标 & lt;/param> | |
/// <param name="message"> 消息内容 & lt;/param> | |
public abstract void Send(string target, string message); | |
/// <summary> | |
/// 接收消息 | |
/// </summary> | |
/// <param name="sender"> 发送者 & lt;/param> | |
/// <param name="message"> 消息内容 & lt;/param> | |
public virtual void Receive(string sender, string message) | |
{ | |
Console.WriteLine(sender + ": " + message); | |
} | |
} | |
} |
namespace BehavioralPatterns_MediatorPattern | |
{ | |
public class PlayerA : Player | |
{ | |
public PlayerA(Mediator mainMediator) : base(mainMediator) | |
{ | |
MainMediator.PlayerDic.Add("PlayerA", this); | |
} | |
public override void Send(string target, string message) | |
{ | |
MainMediator.SendMediator("PlayerA", target, message); | |
} | |
} | |
} |
namespace BehavioralPatterns_MediatorPattern | |
{ | |
public class PlayerB : Player | |
{ | |
public PlayerB(Mediator mainMediator) : base(mainMediator) | |
{ | |
MainMediator.PlayerDic.Add("PlayerB", this); | |
} | |
public override void Send(string target, string message) | |
{ | |
MainMediator.SendMediator("PlayerB", target, message); | |
} | |
} | |
} |
# 中介者
namespace BehavioralPatterns_MediatorPattern | |
{ | |
/// <summary> | |
/// 中介者 | |
/// </summary> | |
public class Mediator | |
{ | |
/// <summary> | |
/// 储存所有的对象 | |
/// </summary> | |
public Dictionary<string, Player> PlayerDic; | |
public Mediator() | |
{ | |
PlayerDic = new Dictionary<string, Player>(); | |
} | |
/// <summary> | |
/// 发送消息的中介 | |
/// </summary> | |
/// <param name="sender"> 发送者 & lt;/param> | |
/// <param name="target"> 目标 & lt;/param> | |
/// <param name="message"> 消息内容 & lt;/param> | |
public void SendMediator(string sender, string target, string message) | |
{ | |
PlayerDic[target].Receive(sender, message); | |
} | |
} | |
} |
# 测试
namespace BehavioralPatterns_MediatorPattern | |
{ | |
public class Program | |
{ | |
private static void Main() | |
{ | |
Mediator mediator = new Mediator(); | |
Player playerA = new PlayerA(mediator); | |
Player playerB = new PlayerB(mediator); | |
playerA.Send("PlayerB", "playerA_message"); | |
} | |
} | |
} |
运行结果:
PlayerA: playerA_message