Friday, June 7, 2013

Mediator Design Patterns in c#

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

class Program
    {
        static void Main(string[] args)
        {
            FacebookGroupMediator m = new FacebookGroupMediator();
            
            Fan fan1 = new Fan(m, "Fan 1");
            FanB fan2 = new FanB(m, "Fan 2");
            Fan fan3 = new Fan(m, "Fan 3");

            fan1.Send("i like this group");
            fan2.Send("yes i also like this group");

            m.Block(fan3.Receive);

            fan1.Send("Do you agree that this is the best group");
            fan2.Send("Yes i agree");
            m.Unblock(fan3.Receive);
            fan1.Send("Thanks all");

            Console.ReadKey();
        }
    }

    class FacebookGroupMediator
    {
        public delegate void CallBack(string message, string from);
        CallBack respond;
        public void SignOn(CallBack method)
        {
            respond += method;
        }
        public void Block(CallBack method)
        {
            respond -= method;
        }
        public void Unblock(CallBack method)
        {
            respond += method;
        }
        //Send is implemented as a broadcast
        public void Send(string message, string from)
        {
            respond(message, from);
        }
    }
    class Fan
    {
        FacebookGroupMediator mediator;
        protected string name;

        public Fan(FacebookGroupMediator mediator, string name)
        {
            this.mediator = mediator;
            mediator.SignOn(Receive);
            this.name = name;
        }
        public virtual void Receive(string message, string from)
        {
            Console.WriteLine(name + " received from " + from + ": " + message);
        }
        public void Send(string message)
        {
            Console.WriteLine("Send (From " + name + "): " + message);
            mediator.Send(message, name);
        }
    }
    class FanB : Fan
    {
        public FanB(FacebookGroupMediator mediator, string name) : base(mediator, name) { }
        //Does not get copies of own messages
        public override void Receive(string message, string from)
        {
            if (!string.Equals(from, name))
                Console.WriteLine(name + " received from " + from + ": " + message);
        }

    }

No comments:

Post a Comment