Template Method Pattern

The Template Method Pattern is a Behavioral Design Pattern that defines the skeleton of an algorithm in a base class and allows subclasses to override specific steps of the algorithm without changing its structure. The base class provides a template method that outlines the general steps of the process, and certain steps are marked as abstract or optional, giving subclasses the flexibility to implement or customize them.

This pattern is useful when you want to standardize the overall process but allow parts of it to vary across different implementations. It is especially useful in scenarios where multiple classes share the same algorithm but have specific steps that differ.

Key Characteristics of Template Method Pattern

  1. Defines an Algorithm Structure:
    • The Template Method Pattern defines the general structure of an algorithm in a base class, leaving some steps to be implemented by subclasses. This approach standardizes the sequence of steps across all subclasses.
  2. Enforces Consistency:
    • The pattern enforces a consistent process, as the overall flow defined by the template method cannot be changed by subclasses. This ensures that all variations of the process follow the same sequence.
  3. Promotes Code Reuse:
    • By providing a base class with a template method, the pattern promotes code reuse, as common steps can be implemented once in the base class, reducing duplication across subclasses.
  4. Adheres to the Open-Closed Principle:
    • The Template Method Pattern adheres to the Open-Closed Principle by allowing subclasses to modify parts of the algorithm (via overridden methods) without modifying the base class’s structure.
  5. Flexibility in Implementation:
    • Subclasses can either implement abstract steps or override existing steps in the base class to customize behavior, making the pattern both flexible and extensible.
  6. Reduces Code Complexity:
    • By encapsulating the algorithm’s structure within a single method, the pattern reduces the complexity of managing steps in different classes, making the overall code easier to understand and maintain.

Template Method Pattern in Node.js

In Node.js, the Template Method Pattern is useful when building applications that require standardized workflows but have steps that can vary depending on the subclass. Let’s illustrate this pattern with an example of a Data Processor that has a general workflow for reading, processing, and saving data, but different subclasses can implement specific data processing steps.

Example Scenario: Data Processor

In this example, we’ll create a DataProcessor base class that defines a template method for reading, processing, and saving data. Different subclasses (e.g., JSON and CSV processors) will implement their own data processing steps.

Step 1: Define the Base Class with the Template Method

The DataProcessor class includes the processData template method, which outlines the general steps. Specific data processing steps are implemented in subclasses.

// Base Class: DataProcessor
class DataProcessor {
  // Template method
  processData() {
    this.readData();
    this.processDataStep();
    this.saveData();
  }

  // General method for reading data
  readData() {
    console.log("Reading data...");
  }

  // Placeholder for processing data (to be implemented by subclasses)
  processDataStep() {
    throw new Error("Method 'processDataStep()' must be implemented.");
  }

  // General method for saving data
  saveData() {
    console.log("Saving data...");
  }
}

Step 2: Create Subclasses with Custom Implementations

Each subclass implements the processDataStep method to handle specific processing logic for different data formats (e.g., JSON and CSV).

// Concrete Class: JSONDataProcessor
class JSONDataProcessor extends DataProcessor {
  processDataStep() {
    console.log("Processing JSON data...");
  }
}

// Concrete Class: CSVDataProcessor
class CSVDataProcessor extends DataProcessor {
  processDataStep() {
    console.log("Processing CSV data...");
  }
}

Step 3: Using the Template Method Pattern

Now, let’s use the JSONDataProcessor and CSVDataProcessor classes to process data in a standardized way.

// Using JSONDataProcessor
const jsonProcessor = new JSONDataProcessor();
jsonProcessor.processData();
/* Output:
Reading data...
Processing JSON data...
Saving data...
*/

// Using CSVDataProcessor
const csvProcessor = new CSVDataProcessor();
csvProcessor.processData();
/* Output:
Reading data...
Processing CSV data...
Saving data...
*/

Explanation:

  • The DataProcessor class defines a general template for processing data, including reading, processing, and saving steps.
  • The processDataStep method is a placeholder, allowing subclasses to provide their own implementations without changing the template method’s structure.

Real-World Examples of Template Method Pattern

  1. Web Scraping and Data Extraction:
    • Web scraping tools often have a similar workflow: fetching a webpage, parsing the HTML, and extracting data. The Template Method Pattern defines the general workflow in a base class and allows subclasses to implement specific extraction steps based on the data structure of different websites.
  2. File Parsing and Data Transformation:
    • File parsers for different file formats (e.g., XML, JSON, CSV) may follow a standardized parsing workflow: loading the file, transforming the data, and saving the results. The Template Method Pattern allows each parser to implement its own transformation logic while keeping the overall workflow consistent.
  3. Payment Processing Systems:
    • In payment processing systems, the steps involved (such as initializing a transaction, verifying payment, and confirming payment) are consistent. The Template Method Pattern enables different payment methods (e.g., credit card, PayPal, bank transfer) to implement their own verification and confirmation logic within the standardized workflow.
  4. User Authentication Workflow:
    • In authentication systems, the workflow for user login generally involves checking credentials, retrieving user data, and validating access permissions. Different authentication types (such as OAuth, JWT, and LDAP) may implement these steps differently. The Template Method Pattern allows the overall process to remain consistent while enabling different authentication methods.
  5. Game Development (Game States):
    • In games, different game states (e.g., start, pause, game over) follow a standard sequence of actions, such as initializing the state, handling user inputs, and rendering graphics. The Template Method Pattern can be used to define the sequence in a base class, with specific states implementing their own logic for input handling and rendering.
  6. Report Generation in Data Analytics:
    • Report generation systems may involve a consistent sequence: loading data, processing it, and formatting it for the report. Different report types (e.g., financial, sales, or customer reports) can implement their own data processing and formatting logic within the standard report generation process.
  7. Cooking Recipe Systems:
    • In recipe applications, each recipe may follow a standard workflow: preparing ingredients, cooking, and serving. Different recipes can implement the specific steps for ingredient preparation and cooking while following the standardized workflow defined in the base class.

Conclusion

The Template Method Pattern is an effective design pattern for structuring algorithms with a consistent workflow while allowing specific steps to vary. By defining the general steps in a base class and delegating customizable parts to subclasses, this pattern promotes code reuse, consistency, and flexibility. The Template Method Pattern is particularly useful in applications that require standardized processes across different implementations, such as file parsing, data transformation, and payment processing.

In Node.js, the Template Method Pattern can be beneficial in applications that need to manage workflows with varying steps, such as data processors, parsers, or task handlers. The pattern improves modularity, reduces code duplication, and enhances maintainability by clearly defining which parts of the process can be customized. By using the Template Method Pattern, developers can create flexible, reusable workflows that adapt to different requirements while maintaining a clear and consistent structure.

Leave a comment

I’m Tran Minh

Hi, I’m Trần Minh, a Solution Architect passionate about crafting innovative and efficient solutions that make technology work seamlessly for you. Whether you’re here to explore the latest in tech or just to get inspired, I hope you find something that sparks joy and curiosity. Let’s embark on this exciting journey together!

Let’s connect