中介者模式:用一个中介对象来封装一系列的对象交互。使各对象不需要显式地相互引用,从而使耦合松散,而且可以独立改变它们之间的交互(中介)。
1 namespace DesignModel.中介模式 2 { 3 ///4 /// 抽象中介者 5 /// 6 abstract class Mediator 7 { 8 public BigGuy bigguy { get; set; } 9 public HiMan himan { get; set; }10 public abstract void Send(string msg, Body body);11 }12 ///13 /// 前台类(通过前台找到公司其他同事)14 /// 15 class QianTai : Mediator16 {17 18 public override void Send(string msg, Body body)19 {20 if (typeof(Body) == typeof(BigGuy))21 {22 himan.Recive(msg);23 }24 else25 {26 bigguy.Recive(msg);27 }28 }29 }30 31 abstract class Body32 {33 protected Mediator med;34 public Body(Mediator mediator)35 {36 med = mediator;37 }38 }39 class BigGuy : Body40 {41 public BigGuy(Mediator med) : base(med) { }42 public void Send(string msg)43 {44 med.Send("", this);45 }46 public void Recive(string msg)47 {48 Console.WriteLine(msg);49 }50 }51 class HiMan : Body52 {53 public HiMan(Mediator med) : base(med) { }54 public void Send(string msg)55 {56 med.Send("", this);57 }58 public void Recive(string msg)59 {60 Console.WriteLine(msg);61 }62 }63 64 }65 66 67 static void 中介模式()68 {69 Mediator qiantai = new QianTai();70 BigGuy bigguy = new BigGuy(qiantai);//同事需要认识前台71 HiMan himan = new HiMan(qiantai);72 qiantai.bigguy = bigguy;//前台需要认识同事73 qiantai.himan = himan;74 75 bigguy.Send("hi, who can fuck me?");76 himan.Send("hi,bigguy,bu yao xiao zhang");77 }
结构上需要注意的是,中介者将具体同事类做为了属性,注意使用时让中介(前台)“认识”(获得依赖)所有同事,让同事都"认识"(获得依赖)中介(前台)。
缺点:随意具体对象数量多到一定程序,中介对象的业务将会变得更加复杂而不好维护。