中介者抽象类(Mediator)定义了同事对象到中介者对象的接口
namespace MediatorPattern.CLASS { abstract class Mediator { public abstract void Send(string message, Colleague colleague); } }
抽象同时类(Colleague)
namespace MediatorPattern.CLASS { abstract class Colleague { protected Mediator mediator; public Colleague(Mediator mediator) { this.mediator = mediator; //获取中介者对象 } } }
具体同事类1(ConCreateColleague1)只知道自己的行为而不知道其他同事,但认识中介者
namespace MediatorPattern.CLASS { class ConCreateColleague1:Colleague { public ConCreateColleague1(Mediator mediator) : base(mediator) { } public void Send(string message) { mediator.Send(message, this); } public void Notify(string message) { Console.WriteLine("同事1得到消息:" + message); } } }
具体同事类2(ConCreateColleague2)只知道自己的行为而不知道其他同事,但认识中介者
namespace MediatorPattern.CLASS { class ConCreateColleague2:Colleague { public ConCreateColleague2(Mediator mediator) : base(mediator) { } public void Send(string message) { mediator.Send(message, this); } public void Notify(string message) { Console.WriteLine("同事2得到消息:" + message); } } }
具体中介者类(ConCreateMediator)认识两个同事,给他们传递信息
namespace MediatorPattern.CLASS { class ConCreateMediator:Mediator { private ConCreateColleague1 colleague1; private ConCreateColleague2 colleague2; /// <summary> /// 同事对象1 /// </summary> public ConCreateColleague1 Colleague1 { set { colleague1 = value; } } /// <summary> /// 同事对象2 /// </summary> public ConCreateColleague2 Colleague2 { set { colleague2 = value; } } public override void Send(string message, Colleague colleague) { if (colleague == colleague1) { colleague2.Notify(message); } else { colleague1.Notify(message); } } } }
测试类(TestMain)同事1发的 Are you sure! ,同事2发的 Yes
using MediatorPattern.CLASS; namespace MediatorPattern { class TestMain { static void Main(string[] args) { ConCreateMediator mediator = new ConCreateMediator(); ConCreateColleague1 colleague1 = new ConCreateColleague1(mediator); ConCreateColleague2 colleague2 = new ConCreateColleague2(mediator); mediator.Colleague1 = colleague1; mediator.Colleague2 = colleague2; colleague1.Send("Are you sure !"); colleague2.Send("Yes!"); } } }
要么忍,要么狠,要么滚!