using System; namespaceMediatorPatternDemo { // The Mediator interface declares a method used by components to notify the // mediator about various events. The Mediator may react to these events and // pass the execution to other components. publicinterfaceIMediator { voidNotify(object sender, string ev); }
// Concrete Mediators implement cooperative behavior by coordinating several // components. classConcreteMediator : IMediator { private Component1 _component1;
publicvoidNotify(object sender, string ev) { if (ev == "A") { Console.WriteLine("Mediator reacts on A and triggers folowing operations:"); this._component2.DoC(); } if (ev == "D") { Console.WriteLine("Mediator reacts on D and triggers following operations:"); this._component1.DoB(); this._component2.DoC(); } } }
// The Base Component provides the basic functionality of storing a // mediator's instance inside component objects. classBaseComponent { protected IMediator _mediator;
// Concrete Components implement various functionality. They don't depend on // other components. They also don't depend on any concrete mediator // classes. classComponent1 : BaseComponent { publicvoidDoA() { Console.WriteLine("Component 1 does A.");
this._mediator.Notify(this, "A"); }
publicvoidDoB() { Console.WriteLine("Component 1 does B.");
this._mediator.Notify(this, "B"); } }
classComponent2 : BaseComponent { publicvoidDoC() { Console.WriteLine("Component 2 does C.");
this._mediator.Notify(this, "C"); }
publicvoidDoD() { Console.WriteLine("Component 2 does D.");
this._mediator.Notify(this, "D"); } }
classProgram { staticvoidMain(string[] args) { Component1 component1 = new Component1(); Component2 component2 = new Component2(); new ConcreteMediator(component1, component2);
// Client triggers operation A. // Component 1 does A. // Mediator reacts on A and triggers following operations: // Component 2 does C.
// Client triggers operation D. // Component 2 does D. // Mediator reacts on D and triggers following operations: // Component 1 does B. // Component 2 does C. } } }