设计模式:中介者模式

Posted uptothesky

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了设计模式:中介者模式相关的知识,希望对你有一定的参考价值。

中介者模式(Mediator):用一个中介对象来封装一序列的对象交互。中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。

技术分享

技术分享
namespace MediatorDesign
{
    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 class ConcreteColleague1:Colleague
    {
        public ConcreteColleague1(Mediator mediator) : base(mediator) { }
        public void Send(string message)
        {
            mediator.Send(message, this);
        }
        public void Notify(string message)
        {
            Console.WriteLine("同事1得到消息:" + message);
        }
    }
    public class ConcreteColleague2 : Colleague
    {
        public ConcreteColleague2(Mediator mediator) : base(mediator) { }
        public void Send(string message)
        {
            mediator.Send(message, this);
        }
        public void Notify(string message)
        {
            Console.WriteLine("同事2得到消息:" + message);
        }
    }
    public class ConcreteMediator : Mediator
    {
        protected ConcreteColleague1 colleague1;
        protected 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);
            }
        }
    }
}
View Code

测试代码:

技术分享
            ConcreteMediator m = new ConcreteMediator();
            ConcreteColleague1 c1 = new ConcreteColleague1(m);
            ConcreteColleague2 c2 = new ConcreteColleague2(m);
            m.Colleague1 = c1;
            m.Colleague2 = c2;
            c1.Send("Hello.");
            c2.Send("Hi.");
View Code

 

以上是关于设计模式:中介者模式的主要内容,如果未能解决你的问题,请参考以下文章

20行为型模式之中介者模式

中介者模式(Mediator Pattern)

中介者模式-Mediator

设计模式之中介者模式 Mediator

23种设计模式--中介者模式-Mediator Pattern

C++设计模式 -中介者模式(Mediator)