设计模式:中介者模式(Mediator)
定 义:用一个中介对象来封装一系列对象的交互。中介者使各个对象不需要显示地相互作用,从而耦合松散,而且可以独立的改变他们之间的交互。
结构图:
Mediator类,抽象中介者类
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
abstract class Mediator { public abstract void Send(string message, Colleague colleague); }
Colleague类,抽象同事类
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
abstract class Colleague { protected Mediator mediator; public Colleague(Mediator mediator) { this.mediator = mediator; } }
ConcreteMediator类,具体中介者类:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//具体中介者类 class ConcreteMediator : Mediator { private ConcreteColleague1 colleague1; private ConcreteColleague2 colleague2; public ConcreteColleague1 Colleague1 { set { colleague1 = value; } } public ConcreteColleague2 Colleague2 { set { colleague2 = value; } } /// <summary> /// 重写发送消息方法,根据对象做出选择对象,做出判断 /// </summary> /// <param name="message"></param> /// <param name="colleague"></param> public override void Send(string message, Colleague colleague) { if (colleague == colleague1) { colleague2.Notify(message); } else { colleague1.Notify(message); } } }
具体同事类:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//具体同事类1 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); } } //具体同事类2 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); } }
客户端调用:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
ConcreteMediator mediator = new ConcreteMediator(); //实例化一个中介者 ConcreteColleague1 colleague1 = new ConcreteColleague1(mediator); //示例化同事1 ConcreteColleague2 colleague2 = new ConcreteColleague2(mediator); //实例化同事2 //让中介者认识各个具体同事类对象 mediator.Colleague1 = colleague1; mediator.Colleague2 = colleague2; //具体同事类对象发送的消息都是通过中介者转发 colleague1.Send("吃饭了吗?"); colleague2.Send("吃了,你呢?");
结果: