Click here to Skip to main content
Click here to Skip to main content
Go to top

Understanding and Implementing Template Method Design Pattern in C#

, 22 Oct 2012
Rate this:
Please Sign up or sign in to vote.

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.".


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.

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.

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.

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.

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();
}

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.


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)

Share

About the Author

Rahul Rajat Singh
Software Developer (Senior)
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[^]
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
SuggestionGood example! PinmemberGena H25-Mar-14 23:18 
QuestionNice explanation PinmemberAkiii0017-Jan-14 21:50 
QuestionUnderstanding and Implementing Template Method Design Pattern in C# Pinmemberrajacsharp530-Dec-13 5:00 
GeneralMy vote of 5 PinmemberJaikrishan20-Mar-13 23:01 

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.140922.1 | Last Updated 23 Oct 2012
Article Copyright 2012 by Rahul Rajat Singh
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid