首页 > 代码库 > Mediator模式

Mediator模式

参考资料《大话设计模式》

Mediator(中介者)模式:

使各个对象不需要显式的相互调用,从而使其耦合松散。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ds_mediator
{
    class Program
    {
        static void Main(string[] args)
        {
            ConcreteMediator m = new ConcreteMediator();
            ConcreteColleage1 c1 = new ConcreteColleage1(m);
            ConcreteColleage2 c2 = new ConcreteColleage2(m);
            m.colleage1 = c1;
            m.colleage2 = c2;
            c1.Send("你好!");
            c2.Send("谢谢!");
        }
    }

    //抽象同事类
    abstract class Colleage
    {
        protected Mediator mediator;
        public Colleage(Mediator mediator)
        {
            this.mediator = mediator;//得到中介者对象
        }
    }
    class ConcreteColleage1 : Colleage
    {
        public ConcreteColleage1(Mediator mediator)
            : base(mediator)
        { }
        public void Send(string message)
        {
            mediator.Send(message, this);
        }
        public void Notify(string message)
        {
            Console.WriteLine("同事1得到消息:" + message);
        }
    }
    class ConcreteColleage2 : Colleage
    {
        public ConcreteColleage2(Mediator mediator)
            : base(mediator)
        { }
        public void Send(string message)
        {
            mediator.Send(message, this);
        }
        public void Notify(string message)
        {
            Console.WriteLine("同事2得到消息:" + message);
        }
    }

    //抽象中介者
    abstract class Mediator
    {
        public abstract void Send(string message, Colleage collgeage);
    }
    class ConcreteMediator : Mediator 
    {
        public ConcreteColleage1 colleage1;
        public ConcreteColleage2 colleage2;

        public override void Send(string message, Colleage colleage)
        {
            if (colleage == colleage1)
            {
                colleage2.Notify(message);
            }
            else
            {
                colleage1.Notify(message);
            }
        }
    }
}