C implements the template method with Lambda and the delegate
- 2020-05-09 19:12:47
- OfStack
1 problem description
Take a look at this code:
int[] a = [1,2,3];
for (int i =0; i<a.length; i++)
{
a[i] = a[i] * 2;
}
for (int i =0; i<a.length; i++)
{
Console.WriteLine(a[i]);
}
Obviously, there is a duplication of the for loop in the code above.
2 solutions
How do you eliminate repetition? Use the delegate.
The & # 8226; Define the entrusted
delegate int mapfun(int x);// To replace the different parts of the code above
The & # 8226; Template method
// It's just traversing
void map(mapfun fn, int[] a)
{
for (int i = 0; i < a.Length; ++i)
{
a[i] = fn(a[i]);
}
}
The & # 8226; Client code
int[] a = {1, 2, 3};
map(delegate(int x) { return x * 2; }, a); //.Net 2.0 Support for delegating anonymous methods
map(x => { Console.WriteLine(x); return x; }, a); //.Net 3.0 To support lambda expression
3 complete code example
class Program
{
static void Main(string[] args)
{
int[] a = {1, 2, 3};
map(delegate(int x) { return x * 2; }, a); //.Net 2.0 Support for delegating anonymous methods
map(x => { Console.WriteLine(x); return x; }, a); //.Net 3.0 To support lambda expression
}
delegate int mapfun(int x);
static void map(mapfun fn, int[] a)
{
for (int i = 0; i < a.Length; ++i)
{
a[i] = fn(a[i]);
}
}
}
4. Comparison with traditional template methods
1. Reduce the number of subclasses. In the template method, one subclass is needed to extend a set of algorithms.
2. The template hides the algorithm and delegates it to the client code for selection.