编辑说明
用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显示地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
/// <summary> /// 抽象中介者 /// </summary> public abstract class Mediator { public abstract void Send(string message, Colleague colleague); }
/// <summary> /// 具体中介者 /// </summary> public class ConcreteMediator : Mediator { private ConcreteColleague1 colleague1; private ConcreteColleague2 colleague2; public ConcreteColleague1 Colleague1 { set { colleague1 = value; } } public ConcreteColleague2 Colleague2 { set { colleague2 = value; } } public override void Send(string message, Colleague colleague) { if (colleague == colleague1) { colleague2.Notify(message); } else { colleague1.Notify(message); } } }
/// <summary> /// 抽象同事类 /// </summary> public abstract class Colleague { protected Mediator mediator; public Colleague(Mediator mediator) { this.mediator = mediator; } }
/// <summary> /// 具体同事类1 /// </summary> public class ConcreteColleague1 : Colleague { public ConcreteColleague1(Mediator mediator) : base(mediator) { } public void Send(string message) { mediator.Send(message, this); } public void Notify(string message) { Console.WriteLine("同事1得到信息:" + message); } }
/// <summary> /// 具体同事类2 /// </summary> public class ConcreteColleague2 : Colleague { public ConcreteColleague2(Mediator mediator) : base(mediator) { } public void Send(string message) { mediator.Send(message, this); } public void Notify(string message) { Console.WriteLine("同事2得到信息:" + message); } }
class Program { static void Main(string[] args) { ConcreteMediator m = new ConcreteMediator(); ConcreteColleague1 c1 = new ConcreteColleague1(m); ConcreteColleague2 c2 = new ConcreteColleague2(m); m.Colleague1 = c1; m.Colleague2 = c2; c1.Send("吃过饭了吗?"); c2.Send("没有呢,你打算请客?"); Console.Read(); } }
降低了类的复杂度,将一对多转化成了一对一。
各个类之间的解耦。
符合迪米特原则。
当对象与对象之间存在大量的关联关系,多个类相互耦合,形成了网状结构,将其变成星型结构。
系统中对象之间存在比较复杂的引用关系,导致它们之间的依赖关系结构混乱而且难以复用该对象。
想通过一个中间类来封装多个类中的行为,而又不想生成太多的子类。
中介者会庞大,变得复杂难以维护。
Demo