中介者模式
中介者模式的核心思想是降低对象间的耦合程度,比如在MVC的架构模式中,C(Controller)就是介于M(Model)和V(View)之间的中介者。
意图:用一个中介对象来封装一系列的对象交互,中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
中介者模式是一种对象行为型模式,其主要优点如下。
- 类之间各司其职,符合迪米特法则。
- 降低了对象之间的耦合性,使得对象易于独立地被复用。
- 将对象间的一对多关联转变为一对一的关联,提高系统的灵活性,使得系统易于维护和扩展。
其主要缺点是:
- 中介者模式将原本多个对象直接的相互依赖变成了中介者和多个同事类的依赖关系。当同事类越多时,中介者就会越臃肿,变得复杂且难以维护。
完整代码如下.
using System;
namespace _16_Mediator
{
/// <summary>
/// 中介者
/// </summary>
class Program
{
//中介者是一种行为设计模式, 让程序组件通过特殊的中介者对象进行间接沟通, 达到减少组件之间依赖关系的目的。
static void Main(string[] args)
{
Component1 component1 = new Component1();
Component2 component2 = new Component2();
new ConcreteMediator(component1, component2);
Console.WriteLine("Client triggets operation A");
component1.DoA();
Console.WriteLine();
Console.WriteLine("Client triggers operation D");
component2.DoD();
Console.ReadKey();
}
}
public interface IMediator
{
void Notify(object sender, string ev);
}
class ConcreteMediator : IMediator
{
private Component1 _component1;
private Component2 _component2;
public ConcreteMediator(Component1 component1,Component2 component2)
{
_component1 = component1;
_component2 = component2;
_component1.SetMediator(this);
_component2.SetMediator(this);
}
public void Notify(object sender,string ev)
{
if (ev == "A")
{
Console.WriteLine("Mediator reacts on A and triggers folowing operations:");
_component2.DoC();
}
if (ev == "D")
{
Console.WriteLine("Mediator reacts on D and triggers following operations:");
_component1.DoB();
_component2.DoC();
}
}
}
class BaseComponent
{
protected IMediator _mediator;
public BaseComponent(IMediator mediator = null)
{
_mediator = mediator;
}
public void SetMediator(IMediator mediator)
{
_mediator = mediator;
}
}
class Component1 : BaseComponent
{
public void DoA()
{
Console.WriteLine("Component 1 does A");
_mediator.Notify(this, "A");
}
public void DoB()
{
Console.WriteLine("Component 2 does B");
_mediator.Notify(this, "B");
}
}
class Component2 : BaseComponent
{
public void DoC()
{
Console.WriteLine("Component 2 does C");
_mediator.Notify(this, "C");
}
public void DoD()
{
Console.WriteLine("Component 2 does D");
_mediator.Notify(this, "D");
}
}
}