Strategy Pattern Using Delegates (Func)- www.Hands-On-Coding.net presentation on Dec 14, 2010

 Strategy Pattern using Func
An alternative to using Strategy pattern using interfaces is Strategy Pattern using delegates.

    •    Create a class with all the different strategies.

 public class Calculator
    {
       public static int Add(int num1, int num2)
       {
           return num1 + num2;
       }

       public static int Subtract(int num1, int num2)
       {
           return num1 - num2;
       }

       public static int Multiply(int num1, int num2)
       {
           return num1 * num2;
       }

       public static int Divide(int num1, int num2)
       {
           return num1 / num2;
       }

    }

    •    Test the code.
int a = 100;
            int b = 50;

            Func<int, int, int> calculate = Calculator.Add;
            int sum = calculate(100, 50);

            calculate = Calculator.Subtract;
            int difference = calculate(100, 50);

            calculate = Calculator.Multiply;
            int product = calculate(100, 50);

If you are new to the syntax, Func. Func is like a delegate that in the above case takes the first two ints as input and outputs the int (third).
Another cool way of using Func is using lambda expressions.

  Func<int, int, int> calculate;
   calculate = (x, s) => x + s;

We could do the above in a single line itself. But what it means is changing the strategly on the fly. Func is a pretty cool feature that reduces a lot of the delegate code we had to write in .NET 2.0. Happy coding !



No Comments