C # Use Lambda and delegate to implement the Template Method

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.