I was looking at this, http://en.wikipedia.org/wiki/Strategy_pattern and I understand the concept of the strategy pattern, but could someone explain the C# example a bit.
I dont really get the how and why of the definition of 'Strategy' in the Context class, why is it Func<T, T, T>
but then just two params are passed in eg 8,9 ?
static void Main(string[] args)
{
var context = new Context<int>();
// Delegate
var concreteStrategy1 = new Func<int, int, int>(PerformLogicalBitwiseOr);
// Anonymous Delegate
var concreteStrategy2 = new Func<int, int, int>(
delegate(int op1, int op2)
{
return op1 & op2;
});
// Lambda Expressions
var concreteStrategy3 = new Func<int, int, int>((op1, op2) => op1 >> op2);
var concreteStrategy4 = new Func<int, int, int>((op1, op2) => op1 << op2);
context.Strategy = concreteStrategy1;
var result1 = context.Execute(8, 9);
context.Strategy = concreteStrategy2;
var result2 = context.Execute(8, 9);
context.Strategy = concreteStrategy3;
var result3 = context.Execute(8, 1);
context.Strategy = concreteStrategy4;
var result4 = context.Execute(8, 1);
}
static int PerformLogicalBitwiseOr(int op1, int op2)
{
return op1 | op2;
}
class Context<T>
{
public Func<T, T, T> Strategy { get; set; }
public T Execute(T operand1, T operand2)
{
return this.Strategy != null
? this.Strategy(operand1, operand2)
: default(T);
}
}