Skip to main content

Understanding the Template Method Design Pattern in C#

 



The Template Method design pattern is a behavioral pattern that defines the skeleton of an algorithm in a base class but allows subclasses to override specific steps of the algorithm without changing its structure. This pattern promotes code reuse, flexibility, maintainability, and ensures a consistent algorithm structure.

Understanding the Strategy Design Pattern in C#

Example Without Template Method Pattern

Let's consider a scenario where we have different types of data processors (e.g., CSV, XML, JSON). Each processor follows a similar sequence of steps: reading the data, processing it, and writing the results. However, the details of these steps vary for each data type. The Template Method pattern is ideal for this scenario.

using System;

namespace WithoutTemplateMethodPattern
{
    class Program
    {
        static void Main(string[] args)
        {
            // Processing CSV data
            ProcessCsvData();

            // Processing XML data
            ProcessXmlData();

            // Processing JSON data
            ProcessJsonData();
        }

        static void ProcessCsvData()
        {
            Console.WriteLine("Reading CSV data...");
            Console.WriteLine("Processing CSV data...");
            Console.WriteLine("Writing CSV data...");
        }

        static void ProcessXmlData()
        {
            Console.WriteLine("Reading XML data...");
            Console.WriteLine("Processing XML data...");
            Console.WriteLine("Writing XML data...");
        }

        static void ProcessJsonData()
        {
            Console.WriteLine("Reading JSON data...");
            Console.WriteLine("Processing JSON data...");
            Console.WriteLine("Writing JSON data...");
        }
    }
}

Problems in the Non-Pattern Approach

  1. Code Duplication:Each method (ProcessCsvData, ProcessXmlData, ProcessJsonData) contains repeated steps (Read, Process, Write). This leads to code duplication and makes maintenance harder.

  2. Lack of Consistency:If the processing steps change (e.g., adding logging or error handling), you need to update each processing method individually. This can lead to inconsistent behavior and increased chances of errors.

  3. Difficulty in Extension:Adding a new data format requires creating a new method with similar code, leading to further duplication. Extending or modifying behavior requires changes in multiple places.

  4. Poor Encapsulation:The individual methods mix the specific processing logic with the sequence of steps. This can lead to a tangled design where the sequence of operations is not clearly separated from the specific operations.
How the Template Method Pattern Solves These Problems
  1. Eliminates Code Duplication:The DataProcessor base class defines the sequence of steps in the ProcessData method. Each concrete class (CsvDataProcessor, XmlDataProcessor, JsonDataProcessor) only provides the specific implementation for the abstract methods (ReadData, Process, WriteData). This reduces code duplication.

  2. Ensures Consistency:The ProcessData method in the base class ensures that the sequence of steps is consistent. Any changes to the sequence need to be made in just one place, ensuring that all subclasses follow the same sequence.

  3. Simplifies Extension:To add a new data format, you only need to create a new subclass and provide implementations for the abstract methods. The ProcessData method remains unchanged, promoting a more maintainable and scalable design.

  4. Encapsulates Sequence Logic:The base class encapsulates the common sequence of operations, while the concrete classes focus solely on the specific implementation details. This separation of concerns makes the design clearer and more modular.

Revisited Code with Template Method Pattern

Here is how we can implement this pattern :

using System;

namespace TemplateMethodPattern
{
    // Abstract base class
    abstract class DataProcessor
    {
        // Template method
        public void ProcessData()
        {
            ReadData();
            Process();
            WriteData();
        }

        // Abstract methods to be overridden by subclasses
        protected abstract void ReadData();
        protected abstract void Process();
        protected abstract void WriteData();
    }

    // Concrete class for CSV data processing
    class CsvDataProcessor : DataProcessor
    {
        protected override void ReadData()
        {
            Console.WriteLine("Reading CSV data...");
        }

        protected override void Process()
        {
            Console.WriteLine("Processing CSV data...");
        }

        protected override void WriteData()
        {
            Console.WriteLine("Writing CSV data...");
        }
    }

    // Concrete class for XML data processing
    class XmlDataProcessor : DataProcessor
    {
        protected override void ReadData()
        {
            Console.WriteLine("Reading XML data...");
        }

        protected override void Process()
        {
            Console.WriteLine("Processing XML data...");
        }

        protected override void WriteData()
        {
            Console.WriteLine("Writing XML data...");
        }
    }

    // Concrete class for JSON data processing
    class JsonDataProcessor : DataProcessor
    {
        protected override void ReadData()
        {
            Console.WriteLine("Reading JSON data...");
        }

        protected override void Process()
        {
            Console.WriteLine("Processing JSON data...");
        }

        protected override void WriteData()
        {
            Console.WriteLine("Writing JSON data...");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            DataProcessor csvProcessor = new CsvDataProcessor();
            csvProcessor.ProcessData();

            DataProcessor xmlProcessor = new XmlDataProcessor();
            xmlProcessor.ProcessData();

            DataProcessor jsonProcessor = new JsonDataProcessor();
            jsonProcessor.ProcessData();
        }
    }
}

Why Can't We Use Other Design Patterns Instead?

  • Strategy Pattern: The Strategy pattern could be used if the steps of the algorithm were completely independent of each other. However, the Template Method pattern is more appropriate when the steps are part of a fixed sequence.
  • Factory Method Pattern: The Factory Method pattern focuses on object creation, not the sequence of steps in an algorithm.
  • Decorator Pattern: The Decorator pattern is used to add responsibilities to objects, not to define a sequence of steps in an algorithm.

Steps to Identify Use Cases for the Template Method Pattern

  1. Identify Common Algorithm Structure: Look for scenarios where multiple subclasses share a common sequence of steps in an algorithm.
  2. Separate Invariant and Variant Steps: Determine which parts of the algorithm are invariant (common) and which are variant (specific to each subclass).
  3. Enforce a Consistent Sequence: Ensure that the overall sequence of steps should remain consistent while allowing variations in individual steps.
  4. Promote Code Reuse and Maintainability: Consider the Template Method pattern when you want to promote code reuse and enhance maintainability by separating common and specific parts of an algorithm.

By following these steps and implementing the Template Method pattern, you can create flexible, reusable, and maintainable code for scenarios that involve a common sequence of steps with specific variations.

Comments

Popular posts from this blog

Implementing and Integrating RabbitMQ in .NET Core Application: Shopping Cart and Order API

RabbitMQ is a robust message broker that enables communication between services in a decoupled, reliable manner. In this guide, we’ll implement RabbitMQ in a .NET Core application to connect two microservices: Shopping Cart API (Producer) and Order API (Consumer). 1. Prerequisites Install RabbitMQ locally or on a server. Default Management UI: http://localhost:15672 Default Credentials: guest/guest Install the RabbitMQ.Client package for .NET: dotnet add package RabbitMQ.Client 2. Architecture Overview Shopping Cart API (Producer): Sends a message when a user places an order. RabbitMQ : Acts as the broker to hold the message. Order API (Consumer): Receives the message and processes the order. 3. RabbitMQ Producer: Shopping Cart API Step 1: Install RabbitMQ.Client Ensure the RabbitMQ client library is installed: dotnet add package RabbitMQ.Client Step 2: Create the Producer Service Add a RabbitMQProducer class to send messages. RabbitMQProducer.cs : using RabbitMQ.Client; usin...

Clean Architecture: What It Is and How It Differs from Microservices

In the tech world, buzzwords like   Clean Architecture   and   Microservices   often dominate discussions about building scalable, maintainable applications. But what exactly is Clean Architecture? How does it compare to Microservices? And most importantly, is it more efficient? Let’s break it all down, from understanding the core principles of Clean Architecture to comparing it with Microservices. By the end of this blog, you’ll know when to use each and why Clean Architecture might just be the silent hero your projects need. What is Clean Architecture? Clean Architecture  is a design paradigm introduced by Robert C. Martin (Uncle Bob) in his book  Clean Architecture: A Craftsman’s Guide to Software Structure and Design . It’s an evolution of layered architecture, focusing on organizing code in a way that makes it  flexible ,  testable , and  easy to maintain . Core Principles of Clean Architecture Dependency Inversion : High-level modules s...

How Does My .NET Core Application Build Once and Run Everywhere?

One of the most powerful features of .NET Core is its cross-platform nature. Unlike the traditional .NET Framework, which was limited to Windows, .NET Core allows you to build your application once and run it on Windows , Linux , or macOS . This makes it an excellent choice for modern, scalable, and portable applications. In this blog, we’ll explore how .NET Core achieves this, the underlying architecture, and how you can leverage it to make your applications truly cross-platform. Key Features of .NET Core for Cross-Platform Development Platform Independence : .NET Core Runtime is available for multiple platforms (Windows, Linux, macOS). Applications can run seamlessly without platform-specific adjustments. Build Once, Run Anywhere : Compile your code once and deploy it on any OS with minimal effort. Self-Contained Deployment : .NET Core apps can include the runtime in the deployment package, making them independent of the host system's installed runtime. Standardized Libraries ...