Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Understanding and Implementing Template Method Design Pattern in C#

4.87/5 (20 votes)
22 Oct 2012CPOL3 min read 62.7K   433  

Introduction

This article talks about the Template method design pattern, when could this pattern be useful and what benefits we can get from it. This article also presents a rudimentary implementation of template design pattern in C#.

Background

There are some scenarios in our application where we would wanna perform some activity but the algorithm to perform that task may vary. Such scenarios can be designed using Strategy pattern so that the basic code that performs the operation will remain the same and the algorithm to perform the task can be switched dynamically. For details on strategy pattern refer: Understanding and Implementing the Strategy Pattern in C# and C++[^]

Now there might be some scenarios where the actual algorithm to perform the task will remain the same but some step of that algorithm can be different from the implementation perspective. Now since the algorithm is same in these scenarios and thus implementing strategy pattern will be an overkill for it. What we can do in such scenarios is that we can use the power of inheritance to achieve this(instead of composition that strategy pattern provides).

The template method pattern is useful in such scenarios where there is an algorithm and some small part of that algorithm may vary. GoF defines Template method pattern as "Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.".

Image 1

In the above shown class diagram

  • AbstractClass: This class mainly contain 2 type of methods. First it contain methods for each step of the algorithm. Second method in this class is the Template method. Template method is the method which used all the individual methods and provides a skeleton for execution of the algorithm.
  • ConcreteClass: This class contain override the methods Abstract class provides for each step of algorithm. They contain the custom implementation of these steps step. This class will contain the default implementation of these steps.

Using the code

Let us now try to look at a sample implementation of this this pattern in C#. Let us assume that we have a class that reads the data from a data source and then creates a file for MIS reporting purpose.

C#
abstract class DataExporter
{
    // This will not vary as the data is read from sql only
    public void ReadData()
    {
        Console.WriteLine("Reading the data from SqlServer");
    }

    // This will not vary as the format of report is fixed.
    public void FormatData()
    {
        Console.WriteLine("Formating the data as per requriements.");
    }

    // This may vary based on target file type choosen
    public abstract void ExportData();        

    // This is the template method that the client will use.
    public void ExportFormatedData()
    {
        this.ReadData();
        this.FormatData();
        this.ExportData();
    }
}

The implementation of the ReadData and FormatData will not change as per the requirements. The only changeable part is the ExportData function whose implementation will change based on the target file to export to. So if we need to export the data to an excel file we need a ConcreteClass for that.

C#
class ExcelExporter : DataExporter
{
    public override void ExportData()
    {
        Console.WriteLine("Exporting the data to an Excel file.");
    }
}

Similarly if we need to export the data to a PDF file we will be needing another concrete class for that overriding only the export part of the algorithm.

C#
class PDFExporter : DataExporter
{
    public override void ExportData()
    {
        Console.WriteLine("Exporting the data to a PDF file.");
    }
}

Now the benefit here is that the DataExporter class will be used by the application and the required implementation of the algorithm will be taken from the derived classes.

C#
static void Main(string[] args)
{
    DataExporter exporter = null;

    // Lets export the data to Excel file
    exporter = new ExcelExporter();
    exporter.ExportFormatedData();

    Console.WriteLine();

    // Lets export the data to PDF file
    exporter = new PDFExporter();
    exporter.ExportFormatedData();
}
Image 2

So we have seen that the actual algorithm to export the data remains the same but the part where the file type to export to can be moved into the derived classes. The template method will remain oblivious to the implementation and will run the algorithm. At run time it will call the derived classes overridden function to execute the required functionality.

Before wrapping up let us look at the class diagram of our dummy application and compare it with the class diagram of Template method pattern.

Image 3

Point of interest

In this article, we have tried to see why and when we might find the template method pattern useful. We have also seen a rudimentary implementation of the template method pattern in C#. Template method pattern is a very good example of the Hollywood principle i.e. "Don't call us, we will call you" in a way that the template method will always remain oblivious to the actual implementation but whenever needed it will call the subclass to get the functionality in place. I hope this small article has been informative.

History

  • 23 October 2012: First version.

License

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