意图
用一个中介对象封装一系列的对象交互.中介者使各对象不需要显式地相互引用,从而使得其耦合松散,而且可以独立地改变他们之间的交互.
比如:有两个人,张三,李四,它们交互非常频繁,那么这两个对象之间耦合性比较强,那么改其中一个对象会对另一个对象产生直接的影响,如果在张三和李四之间加了另外一个中介者,张三和李四之间的交互完全通过中介者来传递,假设张三向和李四说一句话,那么张三就和中介者去说这句话,接着中介者把这句话传到李四这一边,同样李四也是重复这样一个过程.总之中介者是连接各个对象中介的一个角色,也就是说各个对象交互要通过中介者来进行交互,不能互相直接的进行交互.
适用性
1.一组对象以定义良好,但是复杂的方式进行通信.产生的相互依赖关系结构混乱且难以理解.
2.一个对象引用其他很多对象并且直接与这些对象通信,导致难以复用该对象.
3.想定制一个分部在多个类中的行为,而又不想生成太多的子类.
构成:
1.抽象中介者(Mediator):定义一个接口用于各同事对象(Colleague)之间通信.
2.具体中介者(ConcreteMediator):协调各个同事对象实现协作的行为,掌握并且维护它的各个同事对象的引用.
3.同事类(Colleague):每一个同事类对象都引用一个中介者对象,每一个同事对象在需要和其他同事对象通信时,就与它的中介者通信.
ClassDiagram:
SequenceDiagram:
//聊天室示例 class Client { static void Main(string[] args) { ChatRoom c = new ChatRoom(); Participant zhangsan = new ConcreteParticipantA("zhangsan"); Participant lisi = new ConcreteParticipantB("lisi"); Participant wangwu = new ConcreteParticipantA("wangwu"); c.Register(zhangsan); c.Register(lisi); c.Register(wangwu); zhangsan.Send("lisi","hello"); lisi.Send("wangwu","world"); wangwu.Send("zhangsan","helloworld"); Console.ReadKey(); } } /// <summary> /// 抽象中介者类 /// </summary> interface IChatRoom { void Register(Participant participant); void Send(string from, string to, string message); } /// <summary> /// 具体中介者---聊天室类 /// </summary> class ChatRoom : IChatRoom { private Hashtable participants = new Hashtable(); public void Register(Participant participant) { if (participants[participant.Name] == null) { participants[participant.Name] = participant; } participant.ChatRoom = this; } public void Send(String from, string to, string message) { Participant participant = participants[to] as Participant; if (null != participant) { participant.Receive(from, message); } } } /// <summary> /// 抽象同事类(AbstractColleague) /// </summary> abstract class Participant { private ChatRoom chatRoom; private string name; public Participant(string name) { this.name = name; } internal ChatRoom ChatRoom { get { return chatRoom; } set { chatRoom = value; } } public string Name { get { return name; } set { name = value; } } public void Send(string to, string message) { //调用中介者对象相应的Send方法. chatRoom.Send(name, to, message); } public virtual void Receive(string from, string message) { Console.WriteLine("{0} to {1}:{2}", from, name, message); } } /// <summary> /// 具体的同事类(ConcreteColleagueA) /// </summary> class ConcreteParticipantA : Participant { public ConcreteParticipantA(string name) : base(name) { } public override void Receive(string from, string message) { Console.WriteLine("To:" + this.GetType().Name); base.Receive(from, message); } } /// <summary> /// 具体的同事类(ConcreteColleagueB) /// </summary> class ConcreteParticipantB : Participant { public ConcreteParticipantB(string name) : base(name) { } public override void Receive(string from, string message) { Console.WriteLine("To: " + this.GetType().Name); base.Receive(from, message); } }