C#设计模式16——中介者模式的写法

是什么:

中介者模式是一种行为型设计模式,它定义了一个中介者对象来封装一系列对象之间的交互。中介者模式可以使得对象间的交互更加松耦合,避免了对象之间的直接依赖,从而使系统更加灵活、易于扩展和维护。

为什么

中介者模式可以将系统中的对象之间的交互行为进行抽象,从而可以提高系统的可拓展性、可维护性和可读性。同时,它还可以降低系统的复杂度以及对象间的耦合度。

怎么做:

在中介者模式中,我们定义一个中介者接口,中介者负责协调一系列相关对象的交互,并将这些交互行为抽象为中介者接口中的方法。同时,我们还定义了一些相关对象,这些对象直接不再相互交互,而是通过中介者进行交互。相关对象可以保留对中介者的引用,以便于向中介者发送请求。

下面是一个在C#语言中实现中介者模式的示例:

// 中介者接口
public interface IMediator
{
    void SendMessage(string message, Colleague colleague);
}

// 抽象同事类
public abstract class Colleague
{
    protected IMediator mediator;

    public Colleague(IMediator mediator)
    {
        this.mediator = mediator;
    }

    // 定义向中介者发送消息的方法
    public void Send(string message)
    {
        mediator.SendMessage(message, this);
    }

    // 定义接收消息的方法(由子类实现)
    public abstract void Receive(string message);
}

// 具体同事类 A
public class ConcreteColleagueA : Colleague
{
    public ConcreteColleagueA(IMediator mediator) : base(mediator)
    {

    }

    public override void Receive(string message)
    {
        Console.WriteLine("ConcreteColleagueA received message: " + message);
    }
}

// 具体同事类 B
public class ConcreteColleagueB : Colleague
{
    public ConcreteColleagueB(IMediator mediator) : base(mediator)
    {

    }

    public override void Receive(string message)
    {
        Console.WriteLine("ConcreteColleagueB received message: " + message);
    }
}

// 具体中介者类
public class ConcreteMediator : IMediator
{
    private ConcreteColleagueA colleagueA;
    private ConcreteColleagueB colleagueB;

    public ConcreteMediator(ConcreteColleagueA colleagueA, ConcreteColleagueB colleagueB)
    {
        this.colleagueA = colleagueA;
        this.colleagueB = colleagueB;
    }

    public void SendMessage(string message, Colleague colleague)
    {
        if (colleague == colleagueA)
        {
            colleagueB.Receive(message);
        }
        else
        {
            colleagueA.Receive(message);
        }
    }
}

在这个具体的实现中,我们定义了一个中介者接口 IMediator,以及一个抽象同事类 Colleague。Colleague 类中定义了向中介者发送消息的方法 Send() 和接收消息的方法 Receive(),并持有对中介者的引用。接下来,我们定义了两个具体同事类 ConcreteColleagueA 和 ConcreteColleagueB,它们分别实现了 Colleague 类中的 Receive() 方法。最后,我们定义了一个具体中介者类 ConcreteMediator,它持有对两个具体同事类的引用,并实现了 IMediator 接口中的 SendMessage() 方法。在 SendMessage() 方法中,根据接收消息者的不同,转发消息给对应的同事对象。

何时用:

中介者模式通常适用于以下场景:

1.当一个系统中对象之间的交互关系十分复杂,难以维护时,可以考虑采用中介者模式。

2.当一个系统中对象之间的交互是循环的,即对象之间互相引用时,可以考虑采用中介者模式。

3.当一个对象因为要和很多其他对象交互而导致其工作量过大时,可以考虑采用中介者模式。

4.当系统需要支持松耦合,易于维护和扩展时,可以考虑采用中介者模式。

 

posted @ 2023-05-09 22:33  明志德道  阅读(95)  评论(0编辑  收藏  举报