介体模式与具体同事类中的单个介体对象

时间:2013-11-24 12:13:53

标签: c# design-patterns mediator

据我所知,当一组相关对象需要相互通信时,使用中介模式。这是我的以下调解员模式:

    public abstract class MediatorBase
    {
        public abstract void SendMessage(/*ColleaugeBase caller, */IConcreteFunction receiver, string message);
    }

    public class ConcreteMediator : MediatorBase
    {
        public override void SendMessage(/*ColleaugeBase caller, */IConcreteFunction receiver, string message)
        {
            receiver.Notify(message);
        }
    }


public interface IConcreteFunction
    {
        void Send(string message, IConcreteFunction to);
        void Notify(string message);
    }

    public abstract class ColleaugeBase
    {
        protected MediatorBase _mediator;
    }

    public class ConcreteColleauge1 : ColleaugeBase, IConcreteFunction
    {
        public ConcreteColleauge1(MediatorBase mediator)
        {
            _mediator = mediator;
        }

        public void Send(string message, IConcreteFunction to)
        {
            _mediator.SendMessage(/*this,*/ to, message);
        }

        public void Notify(string receiveMessage)
        {
            Console.WriteLine(receiveMessage + " : Message Received by c1");
        }
    }

    public class ConcreteColleauge2 : ColleaugeBase, IConcreteFunction
    {
        public ConcreteColleauge2(MediatorBase mediator)
        {
            _mediator = mediator;
        }

        public void Send(string message, IConcreteFunction to)
        {
            _mediator.SendMessage(/*this,*/ to, message);
        }

        public void Notify(string receiveMessage)
        {
            Console.WriteLine(receiveMessage + " : Message Received by c2");
        }
    }

    public class ConcreteColleauge3 : ColleaugeBase, IConcreteFunction
    {
        public ConcreteColleauge3(MediatorBase mediator)
        {
            _mediator = mediator;
        }

        public void Send(string message, IConcreteFunction to)
        {
            _mediator.SendMessage(/*this,*/ to, message);
        }

        public void Notify(string receiveMessage)
        {
            Console.WriteLine(receiveMessage + " : Message Received by c3");
        }
    }


static void Main(string[] args)
        {
            Project1.MediatorBase mediatorBase = new Project1.ConcreteMediator();

            var c1 = new Project1.ConcreteColleauge1(mediatorBase);
            var c2 = new Project1.ConcreteColleauge2(mediatorBase);
            var c3 = new Project1.ConcreteColleauge3(mediatorBase);

            c1.Send("hellow from c1", c3);
            //c1.Send("hellow from c1", c2);
        }

在这里,我正在为每个通信创建一个新的中介对象。如果只有一个中介对象并且所有同事类共享该单个对象,那么这样做会不会更好。那么,每次通信只会使用一个中介对象吗?

0 个答案:

没有答案