1. Problem Description
View the following code:
Copy codeThe Code is as follows: 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, the for loop already exists in the above Code.
2 solutions
How can we eliminate duplicates? Use delegation.
• Define Delegation
Copy codeThe Code is as follows: delegate int mapfun (int x); // replace different parts of the above Code
• Template Method
Copy codeThe Code is as follows: // only responsible for Traversing
Void map (mapfun fn, int [])
{
For (int I = 0; I <a. Length; ++ I)
{
A [I] = fn (a [I]);
}
}
• Client code
Copy codeThe Code is as follows: int [] a = {1, 2, 3 };
Map (delegate (int x) {return x * 2 ;}, a); //. Net 2.0 supports delegation of anonymous methods
Map (x => {Console. WriteLine (x); return x ;}, a); //. Net 3.0 starts to support lambda expressions
3 complete code example
Copy codeThe Code is as follows: class Program
{
Static void Main (string [] args)
{
Int [] a = {1, 2, 3 };
Map (delegate (int x) {return x * 2 ;}, a); //. Net 2.0 supports delegation of anonymous methods
Map (x => {Console. WriteLine (x); return x ;}, a); //. Net 3.0 starts to support lambda expressions
}
Delegate int mapfun (int x );
Static void map (mapfun fn, int [])
{
For (int I = 0; I <a. Length; ++ I)
{
A [I] = fn (a [I]);
}
}
}
4. Comparison with traditional template Methods
1. The number of subclasses is reduced. In the template method, a subclass is required to expand an algorithm.
2. The template hides the algorithm and delegates it to the customer's code for selection.