Skip to content

Design Patterns: Template Method

Published: at 04:32 PM

Understanding the Template Method Design Pattern

The Template Method design pattern is a behavioral pattern that provides a blueprint for defining the structure of an algorithm while allowing the implementation of specific steps to be deferred to subclasses. This pattern is invaluable for maintaining the order of operations while enabling flexibility in how these operations are performed.

In essence, the Template Method pattern allows a superclass to define the “skeleton” of an operation, leaving the finer details to be implemented by subclasses. This approach ensures that the algorithm’s structure remains consistent while allowing different implementations of its steps.

Why Use the Template Method Pattern?

The Template Method pattern is a fundamental technique for achieving code reuse and enforcing a consistent workflow across various parts of an application. It’s commonly used to remove duplication, enhance extensibility, and ensure that critical steps in a process are executed in the correct order.

As described in the seminal book by the “Gang of Four”:

Template methods are a fundamental technique for code reuse.”

Real-World Use Cases

Here are some scenarios where the Template Method pattern can be highly effective:

The Problem the Template Method Solves

The Template Method pattern is particularly useful in scenarios such as:

Example of Inheritance Without a Template Method

Consider this example:

public abstract class Base
{
    public virtual void Execute()
    {
        ExecuteCommands();
    }
}

public class Child : Base
{
    public override void Execute()
    {
        base.Execute();
        ExecuteDifferentCommands();
    }
}

This approach can lead to issues if a subclass accidentally omits the base.Execute() call, potentially causing the base class’s critical operations to be skipped. Such errors highlight the importance of a pattern like the Template Method, which enforces the execution of specific steps in a predefined order.

Example of a Template Method in Action

Consider the following pseudocode that illustrates the Template Method pattern:

public abstract class DataProcessor
{
    public void ProcessData()
    {
        OpenSource();
        ExtractData();
        TransformData();
        LoadData();
        CloseSource();
    }

    protected abstract void OpenSource();
    protected abstract void ExtractData();
    protected abstract void TransformData();
    protected abstract void LoadData();
    protected abstract void CloseSource();
}

public class FileDataProcessor : DataProcessor
{
    protected override void OpenSource() { /* Open file */ }
    protected override void ExtractData() { /* Read file */ }
    protected override void TransformData() { /* Transform file data */ }
    protected override void LoadData() { /* Insert data */ }
    protected override void CloseSource() { /* Close file */ }
}

public class DatabaseDataProcessor : DataProcessor
{
    protected override void OpenSource() { /* Query database */ }
    protected override void ExtractData() { /* Extract rows */ }
    protected override void TransformData() { /* Transform rows */ }
    protected override void LoadData() { /* Insert rows */ }
    protected override void CloseSource() { /* Close connection */ }
}

In this example, DataProcessor defines the skeleton of a data processing algorithm, while FileDataProcessor and DatabaseDataProcessor provide specific implementations for handling files and databases, respectively.

Structure of the Template Method Pattern

Here’s a diagram illustrating the structure of the Template Method pattern:

AbstractClass
+TemplateMethod() : void
+PrimitiveOperation1()
+PrimitiveOperation2()
+Hook()
ConcreteClass1
+PrimitiveOperation1() : void
+PrimitiveOperation2() : void
ConcreteClass2
+PrimitiveOperation1() : void
+PrimitiveOperation2() : void

In this diagram:

How to Implement the Template Method Pattern

To implement the Template Method pattern:

Refactoring to Follow the Template Method Pattern

To refactor your code to follow the Template Method pattern:

Analysis of the Template Method Pattern

Using the Template Method pattern brings several advantages:

Overall, the Template Method pattern guides developers into the “pit of success” by making it easy to do the right thing and hard to make mistakes.

The Template Method pattern often interacts with other design patterns, such as: