Click here to Skip to main content
15,884,473 members
Articles / Programming Languages / C#
Tip/Trick

How .NET Framework Leverages "Template Method" Design Pattern

Rate me:
Please Sign up or sign in to vote.
4.75/5 (3 votes)
7 Nov 2013CPOL4 min read 13.3K   28   5   1
How Microsoft .NET Framework uses template method design pattern to implement the sorting and searching algorithm.

Introduction

When you complete reading this tip, you will have a deep insight into some of the aspects of the .NET library. You will understand the Template Method design pattern. It also shows how Microsoft .NET Framework has utilized the design pattern "Template Method". This tip also explains how to effectively use the .NET sorting and searching methods.

Background

What is the Template Method design pattern?

Let us start with a class diagram:

fortArticle.JPG

In simplest words, the MyAlgorithm() method in the AbstractClass class is the template method. This method contains the complete algorithm or procedure to complete a task. Let's say its implementation looks like this:

C#
public sealed void MyAlgorithm()
{
// step 1:
// some code here
//step 2: 
operation1();  
 // step 3 
// some code here
// step 4
operation2();
 // step 5 and so on
}   

As you can see, this method is calling the other two methods for completing its task, namely operation 1 and operation 2. The beauty of the template method is that it allows the subclasses to provide the implementation of these two methods. Now these two methods need to be kept abstract so that it becomes a requirement for the subclasses to implement them. When subclasses implement them, then it will be called ultimately whenever MyAlgorithm() gets called. Therefore in the parent class, these two methods are defined as abstract.

Now the ConcreteClass which implements the abstract class contains the implementation of these two methods. Therefore, when the user calls the MyAlgorithm() method, some code will be taken from the abstract class and some code will be taken from the implementing class. In this way, template method design pattern allows the subclasses to provide implementation of some part(s) of the main algorithm.

In this way, the subclasses developer has enough flexibility to provide his own implementation for some part of the algorithm.

How .NET Framework Uses This Pattern?

.NET Framework has utilized this pattern in many locations of the framework taken for demonstration in the sorting algorithm. .NET provides efficient built-in implementation of the sorting algorithm. We can use that built in algorithm in .NET Framework. But the question arises here that how will I tell that what my domain objects are or what an employee is or how to sort a list of employees because .NET does not understand my domain objects. .NET does not know which employee is greater or which employee is lesser, this is pure domain information.

In order to solve this problem, .NET people use the template method. They give a generic sorting algorithm and give us the flexibility to implement some part of that generic algorithm. As we know about our object, and .NET does not, we implement just that part of the algorithm. We can implement which employee is greater than the other and which frame is larger or which employee is smaller or similar and other comparison problems.

In the following code, I have shown how to use the .NET sort method and provide our own implementation for some specific part. You may have done this before, but this time you can review it in the context of the Template Method design pattern.

Using the Code

I am having an unsorted list of special employees. An employee has two fields. Your employee can have many more. I tell the .NET sort method how to sort my special employee. Let us begin with a class diagram:

fortArticle.JPG

My special employee implements the IComparable interface:

C#
class SpecialEmployee : IComparable<SpecialEmployee>  

This is the concrete class which gives the specific implementation. The IComparable interface contains the method CompareTo() where we have to tell how to compare the two objects. This class is similar to the concrete class in the previous class diagram. The code for the compareTo() method is given below:

C#
public int CompareTo(SpecialEmployee secondObject)     {
    // here I will apply the custom logic for 
    //return  0 for equal, 1 for greater and -1 for smaller
    if (this.type == secondObject.type)
    { 
        // if both object id is also same
        if (this.id == secondObject.id)
            return 0;
        // type same other ID is greater
        if (this.id > secondObject.id)
            return 1; 
        if (this.id < secondObject.id)
            return -1;
    } 
    else 
    { 
        // if second object type is 100 that it is large
        if (secondObject.type == 100)
            return 1;
        else
            return -1; 
    } 
    return 0; 
}

As you can see, in the compareTo() method, I tell the .NET framework which employee is greater. In this particular example, type a employees are greater than type b. Similarly, the second condition is using Id. Your object can have many other criteria for sorting.

But wait, where is AbstractClass or where is the generic algorithm? This is implemented in the .NET library itself. We can call the method sort() on the List which is similar to calling the MyAlgorithm() method in the first class diagram. The .NET library may utilize insertion sort, heapsort, or quicksort depending on the size of the data. Following is the code from the main program:

C#
List<SpecialEmployee> allEmployees = GetNotSortedEmployees(); 
allEmployees.Sort(); 

The complete implementation is inside the .NET library whereas .NET library will use our implementation when it comes to specific details of the domain object, which is SpecialEmployee in our case. In the compareTo() method, we tell the .NET Framework which employee is greater than the other.

Points of Interest

This .NET implementation is not the ditto copy of the template method description given above but it utilizes the essence of the template method and provides implementation using interfaces as you may have seen in ASP.NET MVC2 to MVC4.

Many features of the .NET Framework will be easily understood if you have understood the concept of the Template Method design pattern. Advance concepts like LINQ also use this pattern. This design pattern is very common in use. Besides .NET, Java also uses the template method extensively.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Pakistan Pakistan
If you want to learn more about object-oriented design, programming using real-life and real-world examples then you should visit:

www.linesperday.com

You will know what it takes to be great at programming and what lies ahead in your career: Is that money, authority or fame?

My name is Muhammad Umair and I write about programming, programmers, and object-oriented design and how you can optimize your programming skills to advance your programming career.

Comments and Discussions

 
GeneralMy vote of 5 Pin
M Rayhan6-Nov-13 21:39
M Rayhan6-Nov-13 21:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.