旧游无处不堪寻
无寻处,惟有少年心
设计模式-中介者

中介者模式(Mediator Pattern)是一种行为型设计模式,能让你减少对象之间混乱无序的依赖关系。该模式会限制对象之间的直接交互,迫使它们通过一个中介者对象进行合作。

解释


中介者模式让你能在单个中介者对象中封装多个对象间的复杂关系网。类所拥有的依赖关系越少,就越易于修改、扩展或复用。

中介者模式 UML


适用场景


  1. 当一些对象和其他对象紧密耦合以致难以对其进行修改时,可使用中介者模式
  2. 当组件因过于依赖其他组件而无法在不同应用中复用时,可使用中介者模式
  3. 如果为了能在不同情景下复用一些基本行为,导致你需要被迫创建大量组件子类时,可使用中介者模式

代码示例


using System;
namespace MediatorPatternDemo
{
// 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.
public interface IMediator
{
void Notify(object sender, string ev);
}

// Concrete Mediators implement cooperative behavior by coordinating several
// components.
class ConcreteMediator : IMediator
{
private Component1 _component1;

private Component2 _component2;

public ConcreteMediator(Component1 component1, Component2 component2)
{
this._component1 = component1;
this._component1.SetMediator(this);
this._component2 = component2;
this._component2.SetMediator(this);
}

public void Notify(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.
class BaseComponent
{
protected IMediator _mediator;

public BaseComponent(IMediator mediator = null)
{
this._mediator = mediator;
}

public void SetMediator(IMediator mediator)
{
this._mediator = mediator;
}
}

// Concrete Components implement various functionality. They don't depend on
// other components. They also don't depend on any concrete mediator
// classes.
class Component1 : BaseComponent
{
public void DoA()
{
Console.WriteLine("Component 1 does A.");

this._mediator.Notify(this, "A");
}

public void DoB()
{
Console.WriteLine("Component 1 does B.");

this._mediator.Notify(this, "B");
}
}

class Component2 : BaseComponent
{
public void DoC()
{
Console.WriteLine("Component 2 does C.");

this._mediator.Notify(this, "C");
}

public void DoD()
{
Console.WriteLine("Component 2 does D.");

this._mediator.Notify(this, "D");
}
}

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();
// output

// 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.
}
}
}