Back to: Design Patterns in C# With Real-Time Examples
Template Method Design Pattern in C#
In this article, I will discuss the Template Method Design Pattern in C# with Examples. Please read our previous article discussing 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 will discuss the following pointers.
- What is the Template Method Design Pattern?
- Understanding the Template Method Design Pattern with Real-Time Examples
- Implementation of the Template Method Design Pattern in C#.
- Understanding the Class or UML Diagram of Template Method Design Pattern.
- Advantages of Template Method Design Pattern in C#
- When to use the Template Method Design Pattern in Real-Time Applications?
What is the Template Method Design Pattern?
According to the Gang of Four Definition, a 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.
Example to Understand Template Method Design Pattern
Let us understand the Template Method Design Pattern 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.
So, you must follow the above steps to build a concrete house. Suppose you want to build a wooden house. Also, you need to follow the same sequence of steps 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 image below.
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 all the steps (i.e., step1: Building Foundation, Step2: Building Pillars, Step3: Building Walls, Step4: Building Windows) you need to follow to build a house. So, for both houses (Concrete and Wooden), you need to follow the below steps in the sequence shown in the image below.
So, using the Template Method, you can build any 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 named HouseTemplate.cs and copy and paste the following code. 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 will be Concrete Classes, and they should implement the operations defined by the Abstract Class. As we will create two types of houses, i.e., Concrete and Wooden, we will create two concrete classes by implementing the abstract HouseTemplate class and providing implementations for the abstract methods.
ConcreteHouse:
Create a class file named ConcreteHouse.cs and copy and paste the following code. 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 named WoodenHouse.cs and copy and paste the following code. 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
In our example, the Client will be the Main method of the Program class. So, please modify the Main method of the Program class as shown below. Here, we create an object of house type and call the BuildHouse method.
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:
Note: The key idea behind the Template Method Pattern is to let subclasses redefine certain steps of an algorithm without changing the steps’ order.
Use Cases of Template Method Design Pattern:
- When you have a multi-step algorithm, and you want to ensure that the algorithm’s structure remains unchanged while allowing the steps to be overridden by subclasses.
- In scenarios where code duplication can be reduced by generalizing the framework in an abstract class.
Template Method Design Pattern UML or Class Diagram:
Let us understand the Class or UML Diagram of the Template Method Design Pattern and the components involved. Please have a look at the following image.
As you can see in the above image, the State Design Pattern consists of three components. They are as follows:
- AbstractClass: This will be an abstract class containing the template method, which defines the steps to create the product. It also contains abstract methods for each step that subclasses will implement. 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 the concrete child classes will implement.
- 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.
- Client: The Client will use the AbstractClass template method to create different products. In our example, the Client will be the Main method of the Program class. The Main method will use the HouseTemplate class BuildHouse template method to create Concrete and Wooden houses.
Template Method Design Pattern Real-Time Example: Preparing Coffee
Suppose you want to prepare Coffee (let’s say BruCoffee). Then, as shown in the following image, you must follow some steps or procedures such as boiling water, adding milk, adding sugar, and Adding BruCoffee.
Suppose you want to prepare Nescafe Coffee. Also, as shown in the following image, you need to follow the same procedure as BruCofee, such as boiling water, adding milk, adding sugar, and Adding Nescafe Coffee.
If you see both the coffee preparation procedures, it is almost the same, i.e., Boil Water, Add Milk, Add Sugar, Add Coffee type (i.e., Bru and Nescafe), and based on the Coffee type, it will create either Bru Coffee or Nescafe Coffee. So, the procedure for creating coffee is the same. What I can do here is I can create a template method (let us say PrepareCoffee), and within that PrepareCoffee template method, I can define the procedure to create the coffee. For a better understanding, please have a look at the following diagram.
Let us implement the above example step by step using the Template Method Design Pattern in C#.
Step 1: Creating the Template Method
Create a class file named CoffeeTemplate.cs and copy and paste the following code. This will be an abstract class that defines a set of abstract methods that need to be implemented by the concrete subclasses. But if you want, then you can also provide a default implementation, and the child class can optionally override the implementation. This abstract class also provides one concrete method, PrepareCoffee (i.e., template method), which defines the order in which those abstract operations should executed.
using System; namespace TemplateDesignPattern { public abstract class CoffeeTemplate { // PrepareCoffee method is the template method public void PrepareCoffee() { BoilWater(); AddMilk(); AddSugar(); AddCoffeePowder(); Console.WriteLine(this.GetType().Name + " is Ready"); } protected abstract void BoilWater(); protected abstract void AddMilk(); protected abstract void AddSugar(); protected abstract void AddCoffeePowder(); } }
Step 2: Creating Concrete Classes.
The Concrete Classes will implement the operations defined by the Abstract Class. We will create two types of coffees, i.e., BruCoffee and NescafeCoffee. We will create two concrete classes by implementing the abstract CoffeeTemplate class and overriding the abstract methods.
BruCoffee:
Create a class file named BruCoffee.cs, then copy and paste the following code. The following BruCoffee class implements the CoffeeTemplate abstract class and overrides all the abstract methods. This class provides the functionality to create a Bru Coffee.
using System; namespace TemplateDesignPattern { public class BruCoffee : CoffeeTemplate { protected override void BoilWater() { Console.WriteLine("Water Boild"); } protected override void AddMilk() { Console.WriteLine("Milk Added"); } protected override void AddSugar() { Console.WriteLine("Sugar Added"); } protected override void AddCoffeePowder() { Console.WriteLine("Bru Coffee Powder Added"); } } }
NescafeCoffee:
Create a class file named NescafeCoffee.cs and copy and paste the following code. The following NescafeCoffee class implements the CoffeeTemplate abstract class and overrides all the abstract methods. This class provides the functionality to create a Nescafe Coffee.
using System; namespace TemplateDesignPattern { public class NescafeCoffee : CoffeeTemplate { protected override void BoilWater() { Console.WriteLine("Water Boild"); } protected override void AddMilk() { Console.WriteLine("Milk Added"); } protected override void AddSugar() { Console.WriteLine("Sugar Added"); } protected override void AddCoffeePowder() { Console.WriteLine("Nescafe Coffee Powder Added"); } } }
Step3: Client
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 the CoffeeTemplate type and calling the PrepareCoffee method. Based on the object type, it will create appropriate coffee.
using System; namespace TemplateDesignPattern { class Program { static void Main(string[] args) { Console.WriteLine("Nescafe Coffee Preparation\n"); CoffeeTemplate coffee = new NescafeCoffee(); coffee.PrepareCoffee(); Console.WriteLine(); Console.WriteLine("Bru coffee preparation\n"); coffee = new BruCoffee(); coffee.PrepareCoffee(); Console.Read(); } } }
Output:
Advantages of Template Method Design Pattern:
- Code Reusability: Promotes code reusability by allowing common behaviors to be defined in a single place (the abstract class).
- Flexibility and Control: Provides flexibility to subclasses to redefine certain steps of an algorithm without changing its structure.
- Inversion of Control: The higher-level steps of an algorithm are controlled by the parent class, while subclasses handle the details.
When to Use Template Method Design Pattern in C#?
The Template Method Design Pattern in C# is particularly useful in scenarios where:
- Common Workflow with Variations: When there’s a common workflow or series of steps in an algorithm, but some of the steps may vary in their implementation across different contexts or classes.
- Reusing Code Structure: If you want to maximize code reuse by defining the skeleton of an algorithm in a base class and allowing subclasses to redefine certain steps without changing the algorithm’s structure.
- Enforcing a Particular Sequence of Steps: When enforcing a specific sequence of steps in an algorithm while allowing for variation in some of those steps. The Template Method pattern ensures that the overarching sequence is preserved.
- Deferring Implementation to Subclasses: In cases where the exact behavior of some parts of an algorithm can only be determined by subclasses. The pattern allows subclasses to provide these details without changing the algorithm’s structure.
- Preventing Code Duplication: When similar algorithms are present in different classes, this leads to code duplication. The Template Method pattern centralizes the common parts of the algorithms, reducing redundancy.
- Providing Hooks and Extensions: If you want to provide hooks or extension points within an algorithm. Subclasses can extend the algorithm by overriding certain steps while the base algorithm remains unchanged.
- Refactoring Efforts: During refactoring, to consolidate duplicate code across multiple classes. It’s often used to bring common behaviors up into a parent class while allowing for variations in child classes.
- Designing Frameworks or Libraries: When designing frameworks or libraries where, you want to provide users with a fixed template for performing tasks yet allow them to customize certain steps.
In the next article, I will discuss Real-Time Examples of Template Method Design Patterns in C#. In this article, I explain the Template Method Design Pattern in C# with Examples. I hope you enjoy this article.
Registration Open For New Online Training
Enhance Your Professional Journey with Our Upcoming Live Session. For complete information on Registration, Course Details, Syllabus, and to get the Zoom Credentials to attend the free live Demo Sessions, please click on the below links.