Click here to Skip to main content
15,867,568 members
Articles / Programming Languages / C#

Understanding and Implementing Template Method Design Pattern in C#

Rate me:
Please Sign up or sign in to vote.
4.87/5 (20 votes)
22 Oct 2012CPOL3 min read 61.5K   431   19   6

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)


Written By
Architect
India India

I Started my Programming career with C++. Later got a chance to develop Windows Form applications using C#. Currently using C#, ASP.NET & ASP.NET MVC to create Information Systems, e-commerce/e-governance Portals and Data driven websites.

My interests involves Programming, Website development and Learning/Teaching subjects related to Computer Science/Information Systems. IMO, C# is the best programming language and I love working with C# and other Microsoft Technologies.

  • Microsoft Certified Technology Specialist (MCTS): Web Applications Development with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Accessing Data with Microsoft .NET Framework 4
  • Microsoft Certified Technology Specialist (MCTS): Windows Communication Foundation Development with Microsoft .NET Framework 4

If you like my articles, please visit my website for more: www.rahulrajatsingh.com[^]

  • Microsoft MVP 2015

Comments and Discussions

 
QuestionGreat Article. Very well explained. Pin
Rohit Sardana20-Nov-16 23:34
professionalRohit Sardana20-Nov-16 23:34 
QuestionExcellent work Pin
Praveen Raju18-Jun-15 1:19
professionalPraveen Raju18-Jun-15 1:19 
SuggestionGood example! Pin
GenadyT25-Mar-14 23:18
professionalGenadyT25-Mar-14 23:18 
Good example!
I've made some evolution for this sample:

C#
abstract class DataExporter
        {
            protected string _data = "";

            // This will not vary as the data is read from sql only
            public void ReadData(string data)
            {
                _data = data;
            }

            // This will not vary as the format of report is fixed.
            private void FormatData()
            {
                _data = string.Format("(({0}))", _data);
            }

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

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

        class ExcelExporter : DataExporter
        {
            public override string ExportData()
            {
                return string.Format("-- Excel --{0}-- Excel --", _data);
            }
        }

        class PDFExporter : DataExporter
        {
            public override string ExportData()
            {
                return string.Format("** Pdf **{0}** Pdf **", _data);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            DataExporter exporter = null;
            string someData = "I'm a some Data..";

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

            // Lets export the data to PDF file
            exporter = new PDFExporter();
            exporter.ReadData(someData);
            div2.InnerText = exporter.ExportFormatedData();
        }

QuestionNice explanation Pin
Akiii_Lethal7-Jan-14 21:50
Akiii_Lethal7-Jan-14 21:50 
QuestionUnderstanding and Implementing Template Method Design Pattern in C# Pin
rajacsharp530-Dec-13 5:00
rajacsharp530-Dec-13 5:00 
GeneralMy vote of 5 Pin
Jaikrishan20-Mar-13 23:01
Jaikrishan20-Mar-13 23:01 

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.