一、定义
中介者模式, 当多个类彼此关联, 会增大耦合性, 这时各个模块通过中介者进行交流, 每个模块只负责自己的业务逻辑, 不属于自己的就丢给中介者, 降低耦合。
在生活中,例如,你刚刚参力口工作想租房,可以找“房屋中介”;或者,自己刚刚到一个陌生城市找工作,可以找“人才交流中心”帮忙。这都是中介
二、模式的结构与实现
中介者模式实现的关键是找出“中介者”,下面对它的结构和实现进行分析。
1. 模式的结构
中介者模式包含以下主要角色。
- 抽象中介者(Mediator)角色:它是中介者的接口,提供了同事对象注册与转发同事对象信息的抽象方法。
- 具体中介者(ConcreteMediator)角色:实现中介者接口,定义一个 List 来管理同事对象,协调各个同事角色之间的交互关系,因此它依赖于同事角色。
- 抽象同事类(Colleague)角色:定义同事类的接口,保存中介者对象,提供同事对象交互的抽象方法,实现所有相互影响的同事类的公共功能。
- 具体同事类(Concrete Colleague)角色:是抽象同事类的实现者,当需要与其他同事对象交互时,由中介者对象负责后续的交互。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 测试mediator设计模式
{
/// <summary>
/// 抽象中介者
/// </summary>
public abstract class Mediator
{
public abstract void register(Colleague colleague);
public abstract void relay(Colleague cl); //转发
}
/// <summary>
/// 具体中介者
/// </summary>
public class ConcreteMediator : Mediator
{
private List<Colleague> colleagues = new List<Colleague>();
public override void register(Colleague colleague)
{
if (!colleagues.Contains(colleague))
{
colleagues.Add(colleague);
colleague.setMedium(this);
}
}
public override void relay(Colleague cl)
{
foreach (Colleague ob in colleagues)
{
if (!ob.Equals(cl))
{
((Colleague)ob).receive();
}
}
}
}
/// <summary>
/// 抽象同事类
/// </summary>
public abstract class Colleague
{
protected Mediator mediator;
public void setMedium(Mediator mediator)
{
this.mediator = mediator;
}
public abstract void receive();
public abstract void send();
}
/// <summary>
/// 具体同事类1
/// </summary>
public class ConcreteColleague1 : Colleague
{
public override void receive()
{
Console.WriteLine("具体同事类1收到请求。");
}
public override void send()
{
Console.WriteLine("具体同事类1发出请求。");
mediator.relay(this); //请中介者转发
}
}
/// <summary>
/// 具体同事类2
/// </summary>
class ConcreteColleague2 : Colleague
{
public override void receive()
{
Console.WriteLine("具体同事类2收到请求。");
}
public override void send()
{
Console.WriteLine("具体同事类2发出请求。");
mediator.relay(this); //请中介者转发
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 测试mediator设计模式
{
class Program
{
static void Main(string[] args)
{
Mediator md = new ConcreteMediator();
Colleague c1, c2;
c1 = new ConcreteColleague1();
c2 = new ConcreteColleague2();
md.register(c1);
md.register(c2);
c1.send();
Console.WriteLine("-------------");
c2.send();
Console.ReadKey();
}
}
}
三、中介者模式的应用
中介者模式的优点:
减少了类间的依赖, 把原有的一对多的以来变成了一对一的依赖, 同事类只依赖中介者,减少了依赖,当然同时也降低了类间的耦合
中介者模式的缺点:
中介者会膨胀得很大,而且逻辑复杂, 原本N个对象直接的相互依赖关系转换成中介者和同事类的依赖关系, 同事类越多, 中介者的逻辑就越复杂.
中介者模式的使用场景:
中介者模式适用于多个对象之间紧密耦合的情况, 紧密耦合的标准是: 在类图中出现了蜘蛛网状结构. 在这种情况下一定要考虑使用中介者模式, 这有利于把蜘蛛网梳理为星型结构,使原本复杂混乱的关系变得清晰简单
参考:
http://c.biancheng.net/view/1393.html