什么是中介者模式 1 定义 2 例子 3 实现

中介者模式是一种行为设计模式,让程序组件通过特殊的中介者对象进行间接沟通, 达到减少组件之间依赖关系的目的。

中介者能使得程序更易于修改和扩展, 而且能更方便地对独立的组件进行复用, 因为它们不再依赖于很多其他的类。

2 例子

假如有房东,中介,房客三种角色,房东有房子可以出租就通知中介,中介把这条信息通知给所有房客,房客看到信息后进行处理,同理,房客有求助需求,也把求助信息通知给中介,中介把这条信息通知给房东,房东看到信息后进行处理。

3 实现

首先, 声明中介者接口并描述中介者和各种组件之间所需的交流接口。

public interface IMediator
{
    void Notify(object sender, string ev);
}

然后,实现具体中介者类。

class ConcreteMediator : IMediator
{
    private readonly LandlordComponent landlordComponent;
    private readonly TenantComponent tenantComponent;

    public ConcreteMediator(LandlordComponent landlordComponent, TenantComponent tenantComponent)
    {
        this.landlordComponent = landlordComponent;
        this.landlordComponent.SetMediator(this);

        this.tenantComponent = tenantComponent;
        this.tenantComponent.SetMediator(this);
    }

    public void Notify(object sender, string ev)
    {
        if (ev == "求租")
        {
            Console.WriteLine("中介收到求租信息后通知房东。");
            landlordComponent.DoB();
        }
        if (ev == "出租")
        {
            Console.WriteLine("中介收到出租信息后通知房客。");
            tenantComponent.DoD();
        }
    }
}

接着,组件基础类会使用中介者接口与中介者进行交互。

class BaseComponent
{
    protected IMediator mediator;
    public void SetMediator(IMediator mediator)
    {
        this.mediator = mediator;
    }
}    

接着,具体组件房东,房客类,房东不与房客进行交流,只向中介者发送通知。

// 4. 具体组件房东
class LandlordComponent : BaseComponent
{
    public void DoA()
    {
        Console.WriteLine("房东有房子空出来了,向中介发送出租信息。");
        this.mediator.Notify(this, "出租");
    }
    public void DoB()
    {
        Console.WriteLine("房东收到求租信息,进行相应的处理。");
    }
}

// 具体组件房客
class TenantComponent : BaseComponent
{
    public void DoC()
    {
        Console.WriteLine("房客没有房子住了,向中介发送求租信息。");
        this.mediator.Notify(this, "求租");
    }
    public void DoD()
    {
        Console.WriteLine("房客收到出租信息,进行相应的处理。");
    }
}

最后,创建客户端类。

// 客户端代码
class Program
{
    static void Main(string[] args)
    {
        LandlordComponent landlordComponent = new LandlordComponent();
        TenantComponent tenantComponent = new TenantComponent();
        new ConcreteMediator(landlordComponent, tenantComponent);

        landlordComponent.DoA();

        Console.WriteLine();

        tenantComponent.DoC();

        Console.ReadKey();
    }
}

让我们来看看输出结果:

房东有房子空出来了,向中介发送出租信息。
中介收到出租信息后通知房客。
房客收到出租信息,进行相应的处理。

房客没有房子住了,向中介发送求租信息。
中介收到求租信息后通知房东。
房东收到求租信息,进行相应的处理。