What is the Template Method Design Pattern?

Göksu Deniz
8 min readJan 1, 2023

--

Image is created by DALL-E 2 AI

The template method design pattern is a behavioral design pattern that defines the skeleton of an algorithm in a method, called the template method, and allows subclasses to provide the implementation for one or more steps of the algorithm without changing the overall structure of the algorithm.

The template method design pattern is useful when you want to define the basic steps of an algorithm, but allow subclasses to provide specific implementations of some of those steps. This can be useful when you want to provide a high-level structure for an algorithm, but allow subclasses to customize certain parts of it.

The template method design pattern is a way to organize a series of steps that need to be followed in a certain order to complete a task. Imagine you are making a recipe for a cake. The recipe might have a list of steps like this:

  1. Preheat the oven to 350 degrees.
  2. Mix together the flour, sugar, and eggs in a bowl.
  3. Pour the mixture into a cake pan.
  4. Bake the cake for 25 minutes.
  5. Let the cake cool before frosting it.

This is a basic recipe for a cake, and if you followed these steps in order, you would end up with a cake. But what if you wanted to customize the recipe a little bit? Maybe you want to add some chocolate chips to the batter, or you want to bake the cake at a different temperature.

The template method design pattern allows you to take the basic recipe for a cake (the template method) and customize it by changing some of the steps. For example, you might have a subclass of the basic cake recipe that adds chocolate chips to the batter in step 2. This subclass would follow the same basic recipe as the original cake recipe, but it would have a customized version of step 2.

So, to summarize, the template method design pattern is a way to define a series of steps for completing a task, and to allow those steps to be customized by subclasses. It helps to make sure that the steps are followed in the correct order and ensures that the task gets done properly.

Here is an example of the template method design pattern in C#, using the cake-making recipe as an example:

First we are creating out abstract class which has default steps to make cake:

abstract class CakeRecipe
{
public void MakeCake()
{
PreheatOven();
MixIngredients();
PourIntoPan();
Bake();
Cool();
}

protected virtual void PreheatOven()
{
Console.WriteLine("Preheating oven to 350 degrees...");
}

protected virtual void MixIngredients()
{
Console.WriteLine("Mixing together flour, sugar, and eggs in a bowl...");
}

protected virtual void PourIntoPan()
{
Console.WriteLine("Pouring mixture into a cake pan...");
}

protected virtual void Bake()
{
Console.WriteLine("Baking cake for 25 minutes...");
}

protected virtual void Cool()
{
Console.WriteLine("Letting cake cool before frosting it...");
}
}

This was a default steps to make cake. But for alternative cake recipes we can create our concrete classes:

class ChocolateChipCakeRecipe : CakeRecipe
{
protected override void MixIngredients()
{
Console.WriteLine("Mixing together flour, sugar, eggs, and chocolate chips in a bowl...");
}
}

class HighAltitudeCakeRecipe : CakeRecipe
{
protected override void PreheatOven()
{
Console.WriteLine("Preheating oven to 375 degrees (for high altitude baking)...");
}

protected override void Bake()
{
Console.WriteLine("Baking cake for 22 minutes (at high altitude)...");
}
}

OK. Now, we have more than one recipe and we can cook which we want. In the client side it would be look like this:

class Program
{
static void Main(string[] args)
{
CakeRecipe basicCakeRecipe = new CakeRecipe();
basicCakeRecipe.MakeCake();
Console.WriteLine();

CakeRecipe chocolateChipCakeRecipe = new ChocolateChipCakeRecipe();
chocolateChipCakeRecipe.MakeCake();
Console.WriteLine();

CakeRecipe highAltitudeCakeRecipe = new HighAltitudeCakeRecipe();
highAltitudeCakeRecipe.MakeCake();
}
}

Bon appettit!

Here are a few examples of scenarios where the template method design pattern might be used in C#:

  1. You are building a cooking application and want to provide a set of recipes that users can follow. Each recipe has a set of steps that must be completed in a specific order, but the exact actions performed in each step may vary depending on the recipe. The template method pattern could be used to define the overall structure of a recipe (i.e., the set of steps that must be completed), and allow subclasses to provide the specific implementation for each step.
  2. You are building a game engine and want to provide a set of AI behaviors for NPCs (non-player characters). The template method pattern could be used to define the overall structure of an AI behavior (e.g., a sequence of actions to be taken in response to certain stimuli), and allow subclasses to provide the specific implementation for each action.
  3. You are building a data analysis application and want to provide a set of algorithms for processing and visualizing data. The template method pattern could be used to define the overall structure of an algorithm (e.g., a set of steps for cleaning, transforming, and analyzing data), and allow subclasses to provide the specific implementation for each step.
  4. You are building a financial application and want to provide a set of portfolio management strategies. The template method pattern could be used to define the overall structure of a strategy (e.g., a set of steps for selecting, buying, and selling assets), and allow subclasses to provide the specific implementation for each step.
  5. You are building a customer relationship management application and want to provide a set of workflow processes for managing customer interactions. The template method pattern could be used to define the overall structure of a workflow process (e.g., a set of steps for handling customer inquiries, complaints, and requests), and allow subclasses to provide the specific implementation for each step.
  6. You are building a travel application and want to provide a set of itineraries for different types of vacations (e.g., beach vacations, mountain vacations, city breaks). The template method pattern could be used to define the overall structure of an itinerary (e.g., a set of steps for booking flights, hotels, and activities), and allow subclasses to provide the specific implementation for each step.

Here is a sample that how you implement data analysis example on C#:

public abstract class DataAnalysisAlgorithm
{
public void Run()
{
LoadData();
PreprocessData();
AnalyzeData();
VisualizeResults();
}

protected abstract void LoadData();
protected abstract void PreprocessData();
protected abstract void AnalyzeData();
protected abstract void VisualizeResults();
}

public class LinearRegressionAlgorithm : DataAnalysisAlgorithm
{
protected override void LoadData()
{
// Load the data from a CSV file
}

protected override void PreprocessData()
{
// Perform operations such as missing value imputation and feature scaling
}

protected override void AnalyzeData()
{
// Fit a linear regression model to the data
}

protected override void VisualizeResults()
{
// Plot the regression line and display relevant metrics such as R^2 and RMSE
}
}

public class KMeansClusteringAlgorithm : DataAnalysisAlgorithm
{
protected override void LoadData()
{
// Load the data from a database table
}

protected override void PreprocessData()
{
// Perform operations such as outlier detection and normalization
}

protected override void AnalyzeData()
{
// Apply the k-means clustering algorithm to the data
}

protected override void VisualizeResults()
{
// Plot the clusters and display relevant metrics such as the silhouette score
}
}

In this example, the DataAnalysisAlgorithm class defines the overall structure of a data analysis algorithm, including the steps of loading data, preprocessing data, analyzing data, and visualizing results. The LinearRegressionAlgorithm and KMeansClusteringAlgorithm classes are concrete subclasses that provide specific implementations for each of these steps. When the Run() method is called on an instance of either of these subclasses, it will execute the steps defined in the template method in the specified order.

Here is an example for how you use these algorithms on client:

static void Main(string[] args)
{
// Run the linear regression algorithm
DataAnalysisAlgorithm algorithm = new LinearRegressionAlgorithm();
algorithm.Run();

// Run the k-means clustering algorithm
algorithm = new KMeansClusteringAlgorithm();
algorithm.Run();
}

In this example, the client creates an instance of the LinearRegressionAlgorithm class and calls the Run() method on it. This will execute the steps of loading data, preprocessing data, analyzing data, and visualizing results, as defined in the template method of the DataAnalysisAlgorithm class. The client can then create an instance of the KMeansClusteringAlgorithm class and call the Run() method on it in the same way, to execute the steps of a different data analysis algorithm.

Disadvantages

Like all design patterns, the template method pattern has its own set of advantages and disadvantages. Some potential disadvantages of using this pattern include:

  • Complexity: The template method pattern involves creating a hierarchy of classes, which can add complexity to the design of your software. This can make it more difficult to understand and maintain the codebase, especially if the template method and its concrete subclasses are used extensively throughout the application.
  • Code duplication: If you have multiple concrete subclasses that override the same methods in the template method, you may end up with a lot of duplicated code. This can make it more difficult to maintain the codebase, as you will have to update the same code in multiple places if you need to make a change.
  • Overuse: If you use the template method pattern too extensively, you may end up with a large number of classes that are tightly coupled to the template method. This can make it more difficult to reuse these classes in other parts of the application, or to modify their behavior independently of the template method.
  • Limited flexibility: The template method pattern is most useful when you have a set of steps that must be executed in a specific order, but the exact implementation of each step may vary. If you need more flexibility in the order in which steps are executed, or if you need to add additional steps to the process, the template method pattern may not be the best solution.

Overall, the template method pattern can be a useful technique for defining the overall structure of an algorithm or process, but it is important to consider its potential disadvantages when deciding whether it is the right pattern for your specific use case.

Conclusion

In conclusion, the template method design pattern is a useful technique for defining the overall structure of an algorithm or process, while allowing the specific implementation of each step to be customized by concrete subclasses. This can be useful in a variety of real-world scenarios, such as building cooking or game AI applications, or implementing data analysis or customer relationship management systems. By using the template method pattern, you can create a set of flexible, reusable components that can be easily adapted to different requirements, without having to rewrite the code for executing the overall structure of the algorithm or process.

Thanks for reading! If you found the article helpful, you can clap and follow. So you will notified of new articles.

# Reference

It was created with the help of ChatGPT AI.

--

--

Göksu Deniz

Software Engineer, passionate about creating efficient solutions. Skilled in mentoring teams to deliver successful projects. Always exploring new tech trends.