Saturday, October 8, 2011

Implementing a publisher and subscriber with Action Delegate with and without parameters


I usually used to declare a delegate and event as separate declarations to build a publisher and subscriber mechanism. I found an alternate mechanism to accomplish the same
The concept that came to my help was Action Delegate.

  I followed the steps below
1.  Create 2 classes publisher and Subscriber
2.  Declare the Action Delegate in the Publisher class
3.  Hook the action Delegate to the event handler in Subscriber
4.  Raise the event in any of the publisher functions

The example below demonstrates the use of Action delegate with no parameters and Parameterised Action delegates

class Publisher
    {

        /// <summary>
        /// Action delegate without parameter
        /// </summary>
        public Action Completed;

        /// <summary>
        /// Parameterised Action Delegate
        /// </summary>
        public Action<int, string, string> ParameterizedCompleted;

        public void PublishParameterisedAction()
        {

            string str1 = "Hello";
            string str2 = "World";
            StringBuilder builder = new StringBuilder();
            builder.Append(str1);
            builder.Append(str2);
            int length = builder.Length;

            //Raise an event with parameters
            ParameterizedCompleted(length, str1, str2);

        }


        public void PublishAction()
        {
            string str1 = "Hello";
            string str2 = "World";
            StringBuilder builder = new StringBuilder();
            builder.Append(str1);
            builder.Append(str2);
            int length = builder.Length;

            //Raise an event without parameters
           Completed();



        }





    class Subscriber
    {
        

        static void Main(string[] args)
        {
            Publisher publisher = new Publisher();
            publisher.Completed += new Action(handleCompleted);
            publisher.ParameterizedCompleted += new Action<int, string, string>(handleTemplateCompleted);
            publisher.PublishAction ();
            publisher.PublishParameterisedAction ();

            Console.ReadLine();
        }

       static  void handleTemplateCompleted(int length,string str1 ,string  str2)
        {
            Console.Write("Result from TemplateCompletedAction" + length + str1 + str2);
        }

      static  void handleCompleted()
       {

           Console.WriteLine("notification recieved");
       }

      
    }



No comments: