Friday, June 7, 2013

Mediator Design Patterns (Behavioral Patterns) in C#

Mediator: The mediator pattern encapsulate the interaction between a set of objects.

class Program
    {
        static void Main(string[] args)
        {
            IColleague<string> colleagueA = new ConcreteColleague<string>("Colleague A");
            IColleague<string> colleagueB = new ConcreteColleague<string>("Colleague B");
            IColleague<string> colleagueC = new ConcreteColleague<string>("Colleague C");

            //First Mediator
            IMediator<string> mediator1 = new ConcreteMediator<string>();

            //participants registers to the mediator
            mediator1.Register(colleagueA);
            mediator1.Register(colleagueB);
            mediator1.Register(colleagueC);

            //Participant A sends out a message
            colleagueA.SendMessage(mediator1, "Message from colleague A");

            //second mediator
            IMediator<string> mediator2=new ConcreteMediator<string>();
            mediator2.Register(colleagueB);
            mediator2.Register(colleagueC);

            //participant B sends out a message
            colleagueB.SendMessage(mediator2,"Message from colleague B");

            Console.ReadKey();
        }
    }


    public interface IMediator<t>
    {
        List<IColleague<t>> colleagueList { get; }
        void DistributeMessage(IColleague<t> sender, t message);
        void Register(IColleague<t> colleague);
    }
    public interface IColleague<t>
    {
        void SendMessage(IMediator<t> mediator, t message);
        void ReceiveMessage(t message);
    }
    public class ConcreteColleague<t> : IColleague<t>
    {
        private string name;
        public ConcreteColleague(string name)
        {
            this.name = name;
        }

        public void SendMessage(IMediator<t> mediator, t message)
        {
            mediator.DistributeMessage(this, message);
        }

        public void ReceiveMessage(t message)
        {
            Console.WriteLine(this.name + " received " + message.ToString());
        }
    }
    public class ConcreteMediator<t> : IMediator<t>
    {
        private List<IColleague<t>> lstcolleague = new List<IColleague<t>>();
        public List<IColleague<t>> colleagueList
        {
            get { return lstcolleague; }
        }

        public void DistributeMessage(IColleague<t> sender, t message)
        {
            foreach (IColleague<t> c in lstcolleague)
            {
                if (c != sender)//don't need to send message to sender
                    c.ReceiveMessage(message);
            }
        }

        public void Register(IColleague<t> colleague)
        {
            lstcolleague.Add(colleague);
        }

    }

No comments:

Post a Comment