中介者模式

The Mediator design pattern defines an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping from refering to each ohter explicitly, and it lets you vary their interaction independently.

中介者模式定义了一个对象封装了一系列对象的交互,中介者模式通过防止对象显示地调用来促进松耦合,并且允许你独立地改变它们之间交互。

UML

 组成元素

Meditor:定义一个接口用于和Colleage objects之间的通信

ConcreteMediator:

  • 通过协调Colleage objects实现协作行为
  • 了解并保持Colleage objects

Colleage classes

  • 每个Colleage class作为一个中介者对象
  • 每个Colleage和Mediator通信时它都会与其他Colleage object通信

Structure Code IN C#

    public abstract class Colleague
    {
        public IMediator? meditor;
        protected string Name;

        public Colleague(String name)
        {
            this.Name = name;
        }
        public abstract void Send(string message);
        public abstract void Receive(string message);    
    }

    public class ConcreteColleague : Colleague
    {
        public ConcreteColleague(string name) : base(name)
        {
        }

        public override void Send(string message)
        {
            Console.WriteLine($"{this.Name} sending message {message}");
            meditor?.SendMessage(message, this);
        }

        public override void Receive(string message)
        {
            Console.WriteLine($"{this.Name} receiving message {message}");
        }
    }
Colleague 
    public interface IMediator
    {
        void SendMessage(string msg, Colleague colleague);
        void RegisterColleague(Colleague colleague);
    }

    public class ConcreteMediator : IMediator
    {
        private List<Colleague> colleagues = new List<Colleague>();

        public void RegisterColleague(Colleague colleague)
        {
            colleague.meditor = this;
            colleagues.Add(colleague);
        }

        public void SendMessage(string msg, Colleague colleague)
        {
            colleagues.ForEach(c => 
            {
                if (c != colleague)
                    c.Receive(msg);
            });
        }
    }
Mediator 

使用场景:

  • We can communication between multiple objects to be well defined but potentially complex.当我们想在多个对象间相互通信但可能比较复杂的情况下。
  • we have too many relationships that exist and a common point of control or communication is required.当我们有太多的关系存在,需要一个公共的控制点或沟通点。

 

posted @ 2023-06-03 21:35  云霄宇霁  阅读(7)  评论(0编辑  收藏  举报