Template Method Design Pattern in C#

Template Method Design Pattern in C#

In this article, I am going to discuss the Template Method Design Pattern in C# with Examples. Please read our previous article where we discussed State Design Patterns in C# with Examples. The Template Method Design Pattern falls under the category of behavioral Design Pattern. As part of this article, we are going to discuss the following pointers.

  1. What is the Template Method Design Pattern?
  2. Understanding the Template Method Design Pattern with Real-Time Examples
  3. Implementation of the Template Method Design Pattern in C#.
  4. Understanding the Class or UML Diagram of Template Method Design Pattern.
  5. When to use the Template Method Design Pattern in Real-Time Applications?
What is the Template Method Design Pattern?

According to Gang of Four, Template Method Design Pattern defines a sequence of steps of an algorithm and allows the subclasses to override the steps but is not allowed to change the sequence

Let us understand the above definition with an example. Suppose you want to build a concrete house, then you need to follow a sequence of steps i.e. first you need to build a foundation, then you need to build Pillars. Then, you need to build Walls and finally, you need to build Windows as shown in the below image.

What is the Template Method Design Pattern?

So, you have to follow the above sequence of steps in order to build a concrete house. Suppose you want to build a wooden house. Then also you need to follow the same sequence of steps that you follow in order to build a concrete house i.e. first you need to build the foundation, then you need to build Pillars, then Walls, and Finally Windows as shown in the below image.

Understanding the Template Method Design Pattern with Real-Time Examples

The only difference here is instead of using Concrete you need to use Wooden Materials. So, what you can do here is, you can define a Template Method (called Build a House). The template method will define what are all the steps (i.e. step1: Building Foundation, Step2: Building Pillars, Step3: Building Walls, Step4: Building Windows) that you need to follow in order to build a house. So, for both the houses (Concrete and Wooden), you need to follow the below steps in the sequence as shown in the below image.

When to use the Template Method Design Pattern in Real-Time Applications?

So, using the Template Method you can build any type of house (Wooden, Glass, Concrete, etc).

How to Implement Template Method Design Pattern in C#?

Let us implement the above example (Building House) using Template Method Design Pattern in C# step by step.

Step 1: Creating Template Method in Abstract Class

Create an abstract class with the name HouseTemplate.cs and then copy and paste the following code into it. This Abstract Class defines a set of abstract methods that need to be implemented by the Concrete Sub Classes. But if you want you can also provide a default implementation for the above methods and the child class can optionally override the implementation if required. It also provides one concrete method BuildHouse (i.e. Template Method) which defines the order in which those abstract operations should occur. 

using System;
namespace TemplateMethodDesignPattern
{
    public abstract class HouseTemplate
    {
        // Template Method defines the sequence for building a house
        public void BuildHouse()
        {
            //Define the Steps to Build a House
            BuildFoundation(); //Step1
            BuildPillars(); //Step2
            BuildWalls(); //Step3
            BuildWindows(); //Step4
            Console.WriteLine("House is Built");
        }

        // Methods to be implemented by subclasses
        protected abstract void BuildFoundation();
        protected abstract void BuildPillars();
        protected abstract void BuildWalls();
        protected abstract void BuildWindows();
    }
}
Step 2: Creating Concrete Classes

These are going to be Concrete Classes and they should implement the operations defined by the Abstract Class. As we are going to create two types of houses i.e. Concrete and Wooden, so we are going to create two concrete classes by implementing the abstract HouseTemplate class and providing implementations for the abstract methods.

ConcreteHouse:

Create a class file with the name ConcreteHouse.cs and then copy and paste the following code into it. The following class code is very straightforward. The following class implements the HouseTemplate abstract class and overrides all the abstract methods. This class provides the functionality to create a concrete house.

using System;
namespace TemplateMethodDesignPattern
{
    public class ConcreteHouse : HouseTemplate
    {
        protected override void BuildFoundation()
        {
            Console.WriteLine("Building foundation with cement, iron rods and sand");
        }

        protected override void BuildPillars()
        {
            Console.WriteLine("Building Concrete Pillars with Cement and Sand");
        }

        protected override void BuildWalls()
        {
            Console.WriteLine("Building Concrete Walls");
        }

        protected override void BuildWindows()
        {
            Console.WriteLine("Building Concrete Windows");
        }
    }
}
WoodenHouse:

Create a class file with the name WoodenHouse.cs and then copy and paste the following code into it. The following class also implements the HouseTemplate abstract class and overrides all the abstract methods. This class provides the functionality to create a wooden house.

using System;
namespace TemplateMethodDesignPattern
{
    public class WoodenHouse : HouseTemplate
    {
        protected override void BuildFoundation()
        {
            Console.WriteLine("Building foundation with cement, iron rods, wood and sand");
        }

        protected override void BuildPillars()
        {
            Console.WriteLine("Building wood Pillars with wood coating");
        }

        protected override void BuildWalls()
        {
            Console.WriteLine("Building Wood Walls");
        }

        protected override void BuildWindows()
        {
            Console.WriteLine("Building Wood Windows");
        }
    }
}
Step 3: Client

The Main method of the Program class is going to be the Client in our example. So, please modify the Main method of the Program class as shown below. Here, we are creating an object of house type and calling the BuildHouse method. The following class code is self-explained, so please go through the comment lines for a better understanding.

using System;
namespace TemplateMethodDesignPattern
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Build a Concrete House\n");
            HouseTemplate houseTemplate = new ConcreteHouse();
            //Call the Template Method to Build the Concrete House
            houseTemplate.BuildHouse();

            Console.WriteLine();

            Console.WriteLine("Build a Wooden House\n");
            houseTemplate = new WoodenHouse();
            //Call the Template Method to Build the Wooden House
            houseTemplate.BuildHouse();

            Console.Read();
        }
    }
}
Output:

Template Method Design Pattern in C# with Examples

Template Method Design Pattern UML or Class Diagram:

Let us understand the Class or UML Diagram of the Template Method Design Pattern and understand the different components involved. Please have a look at the following image.

UML or Class Diagram

As you can see in the above image, the State Design Pattern consists of three components. They are as follows:

  1. AbstractClass: This is going to be an abstract class that contains the template method which defines the steps to create the product. It also contains abstract methods for each of the steps that are going to be implemented by subclasses. In our example, HouseTemplate abstract class. Here, BuildHouse is the Template method that defines the steps or sequence to build a house. It also defines BuildFoundation, BuildPillars, BuildWalls, and BuildWindows abstract methods which are going to be implemented by the concrete child classes.
  2. ConcreteClassA/B: These are going to be concrete classes and these classes are inherited from the abstract class and override the abstract class abstract methods in their own way. In our example, it is the ConcreteHouse, and WoodenHouse concrete classes and these two classes inherit from the HouseTemplate abstract class and override the BuildFoundation, BuildPillars, BuildWalls, and BuildWindows abstract methods.
  3. Client: The Client is going to use the AbstractClass template method to create different products. In our example, the Main method of the Program class is going to be the Client. And the Main method going to use the HouseTemplate class BuildHouse template method to create Concrete as well as Wooden houses.
When to use Template Method Design Patterns in Real-Time Applications?

We need to use the Template Method Design Pattern in Real-Time Applications when

  1. We have a method in the base class that calls a bunch of other methods that are either abstract or empty in a particular sequence.
  2. We required an abstract view of an algorithm, but the implementation of the algorithm varies according to the child classes.

In the next article, I am going to discuss Real-Time Examples of Template Method Design Patterns in C#. Here, in this article, I try to explain the Template Method Design Pattern in C# with Examples. I hope you enjoy this article.

Leave a Reply

Your email address will not be published. Required fields are marked *