Skip to content

中介者(Mediator)模式 行为型模式

更新: 2023-05-24 11:11:27   字数: 0 字   时长: 0 分钟

定义一个中介对象来简化原有对象之间的交互关系,降低系统中对象间的耦合度,使原有对象之间不必相互了解。

c#
// 中介者模式示例
using System;

// 定义抽象中介者类
public abstract class Mediator
{
    public abstract void Send(string message, Colleague colleague);
}

// 定义抽象同事类
public abstract class Colleague
{
    protected Mediator mediator;

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

    public virtual void Send(string message)
    {
        mediator.Send(message, this);
    }

    public abstract void Notify(string message);
}

// 具体中介者类
public 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);
        }
    }
}

// 具体同事类1
public class ConcreteColleague1 : Colleague
{
    public ConcreteColleague1(Mediator mediator)
        : base(mediator)
    {
    }

    public override void Notify(string message)
    {
        Console.WriteLine("同事1得到消息:" + message);
    }
}

// 具体同事类2
public class ConcreteColleague2 : Colleague
{
    public ConcreteColleague2(Mediator mediator)
        : base(mediator)
    {
    }

    public override void Notify(string message)
    {
        Console.WriteLine("同事2得到消息:" + message);
    }
}

// 客户端调用
class Program
{
    static void Main(string[] args)
    {
        ConcreteMediator mediator = new ConcreteMediator();

        ConcreteColleague1 colleague1 = new ConcreteColleague1(mediator);
        ConcreteColleague2 colleague2 = new ConcreteColleague2(mediator);

        mediator.Colleague1 = colleague1;
        mediator.Colleague2 = colleague2;

        colleague1.Send("你好,同事2!");
        colleague2.Send("你好,同事1!");

        Console.Read();
    }
}
你觉得这篇文章怎么样?
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0
评论
  • 按正序
  • 按倒序
  • 按热度