中介者模式:是用来降低多个对象和类之间的通信复杂性。这种模式提供了一个中介类,该类通常处理不同类之间的通信,并支持松耦合,使代码易于维护。中介者模式属于行为型模式。
主要意图:用一个中介对象来封装一系列的对象交互,中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
主要解决:对象与对象之间存在大量的关联关系,这样势必会导致系统的结构变得很复杂,同时若一个对象发生改变,我们也需要跟踪与之相关联的对象,同时做出相应的处理。
解决方案:将上述网状结构分离为星型结构。
优点:
1、降低了类的复杂度,将一对多转化成了一对一。
2、各个类之间的解耦。
3、符合迪米特原则。
缺点:
中介者会庞大,变得复杂难以维护。
中介者模式类图:
代码实现:
客户端代码:
using System;
namespace _01中介者模式_结构图
{
class Program
{
static void Main(string[] args)
{
ConcreteMediator m = new ConcreteMediator();
ConcreteColleague1 c1 = new ConcreteColleague1(m);
ConcreteColleague2 c2 = new ConcreteColleague2(m);
m.Colleague1 = c1;
m.Colleague2 = c2;
c1.Send("吃过饭了吗?");
c2.Send("没有呢,你打算请客?");
Console.Read();
}
}
}
抽象中介者类:
using System;
using System.Collections.Generic;
using System.Text;
namespace _01中介者模式_结构图
{
/// <summary>
/// 抽象中介者类
/// </summary>
abstract class Mediator
{
public abstract void Send(string message, Colleague colleague);
}
}
具体中介者类:
using System;
using System.Collections.Generic;
using System.Text;
namespace _01中介者模式_结构图
{
/// <summary>
/// 具体中介者类
/// </summary>
class ConcreteMediator : Mediator
{
private ConcreteColleague1 colleague1;
private ConcreteColleague2 colleague2;
public ConcreteColleague1 Colleague1
{
set { colleague1 = value; }
}
public ConcreteColleague2 Colleague2
{
set { colleague2 = value; }
}
public override void Send(string message, Colleague colleague)
{
if (colleague == colleague1)
{
colleague2.Notify(message);
}
else
{
colleague1.Notify(message);
}
}
}
}
抽象同事类:
using System;
using System.Collections.Generic;
using System.Text;
namespace _01中介者模式_结构图
{
/// <summary>
/// 抽象同事类
/// </summary>
abstract class Colleague
{
protected Mediator mediator;
public Colleague(Mediator mediator)
{
this.mediator = mediator;
}
}
}
据图同事类:
using System;
using System.Collections.Generic;
using System.Text;
namespace _01中介者模式_结构图
{
/// <summary>
/// 各种同事对象
/// </summary>
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);
}
}
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);
}
}
}
zongjie 总结:
中介者对象封装了一系列的对象交互,中介者使各对象不需要彼此联系来相互作用,从而使耦合松散,而且可以独立的改变他们之间的交互。