中介模式(Mediator):
用一个中介对象,来封装一系列的对象交互。中介者使个对象不需要显式地相互引用,从而使其耦合松散,并且可以独立地改变他们之间的交互。
一、UML结构图
二、示例代码
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 /* 7 * 中介模式:就像租房中介一样 8 * 房东,不了解租户信息,但知道中介(Colleague1) 9 * 租户:不了解房东信息,但知道中介(Colleague2) 10 * 中介:需要知道房东和租户,并在中介做调和。(ConcreteMediator) 11 */ 12 namespace 中介者模式 13 { 14 class Program 15 { 16 static void Main(string[] args) 17 { 18 //中介者 19 Mediator m = new ConcreteMediator(); 20 //同事1 21 Colleague c1 = new ConcreteColleagueA(m); 22 //同事2 23 Colleague c2 = new ConcreteColleagueB(m); 24 25 m.colleague1=c1; 26 m.colleague2=c2; 27 28 c1.Send("你好,我是C1."); 29 c2.Send("你好,我是C2."); 30 31 Console.Read(); 32 } 33 } 34 35 /// <summary> 36 /// 中介基类 37 /// </summary> 38 public abstract class Mediator 39 { 40 /// <summary> 41 /// 发送消息(将两个对象间,需要进行的耦合操作行为,进行抽象) 42 /// </summary> 43 /// <param name="msg">发送的内容</param> 44 /// <param name="colleague">发送人</param> 45 public abstract void Send(string msg, Colleague colleague); 46 47 public Colleague colleague1 { get; set; } 48 public Colleague colleague2 { get; set; } 49 } 50 51 public class ConcreteMediator:Mediator 52 { 53 54 public override void Send(string msg, Colleague colleague) 55 { 56 //中介在接收到消息,并发送时,可以对消息进行处理 57 58 //处理后,进行发送 59 if (colleague == colleague1) 60 colleague2.Notify(msg, colleague); 61 else 62 colleague1.Notify(msg, colleague); 63 } 64 } 65 66 67 /// <summary> 68 /// Colleague 同事、同僚 69 /// </summary> 70 public abstract class Colleague 71 { 72 protected Mediator m_Mediator; 73 public Colleague(Mediator mediator) 74 { 75 m_Mediator = mediator; 76 } 77 78 public abstract void Send(string msg); 79 public abstract void Notify(string msg,Colleague sendColleague); 80 81 } 82 83 public class ConcreteColleagueA:Colleague 84 { 85 public ConcreteColleagueA(Mediator mediator) 86 : base(mediator) 87 { 88 89 } 90 91 public override void Send(string mes) 92 { 93 m_Mediator.Send(mes, this); 94 } 95 96 public override void Notify(string msg, Colleague sendColleague) 97 { 98 Console.WriteLine(string.Format("接收到{0}的消息{1}.",sendColleague.ToString(),msg)); 99 } 100 101 public override string ToString() 102 { 103 return "ConcreteColleagueA"; 104 } 105 } 106 public class ConcreteColleagueB : Colleague 107 { 108 public ConcreteColleagueB(Mediator mediator) 109 : base(mediator) 110 { 111 112 } 113 114 public override void Send(string mes) 115 { 116 m_Mediator.Send(mes, this); 117 } 118 public override void Notify(string msg, Colleague sendColleague) 119 { 120 Console.WriteLine(string.Format("接收到{0}的消息{1}.", sendColleague.ToString(), msg)); 121 } 122 123 public override string ToString() 124 { 125 return "ConcreteColleagueB"; 126 } 127 } 128 129 }
三、作用
优点:
1、减少了各个Colleague的耦合,使其可以独立的改变和复用各个Colleague和Mediator
2、将Colleague对象间的协作进行了抽象,这样关注的对象,就从对象本身转移到了协作交互上来了,角度更为宏观了。
缺点:
1、中介类控制了集中化,于是就把交互复杂性转移到了中介者身上,这就是中介者更为复杂。