Design Smarter : The Template Method Approach

 

Template Method Pattern

 


The Template Method Pattern is a behavioral design pattern that defines the skeleton of an algorithm in a method, deferring some steps to subclasses. It allows subclasses to override certain steps of the algorithm without changing its structure. The pattern promotes code reuse and helps in defining a common structure for a group of related algorithms.

Key Participants:

Abstract Class

·         Defines the template method (templateMethod()) that outlines the steps of the algorithm. This method typically consists of a sequence of method calls, some of which are abstract and need to be implemented by subclasses.

May contain concrete methods that are shared across all subclasses.

Concrete Classes:

·         Subclasses of the abstract class that implement the abstract methods defined in the template method.

·         Each concrete class provides its own implementation for the abstract methods, customizing the algorithm's behavior.

Example Explanation

The Template Method Pattern in this example allows you to define a skeleton of an algorithm (readProcessSave()) in an abstract class (MainDataProcess), with specific steps (readData(), processData(), saveData()) that can be customized by subclasses (ExcelFile and WordFile). This promotes code reuse, maintains a consistent structure across different implementations, and allows for flexible customization of specific behaviors within a defined process flow.

1.Abstract Class (MainDataProcess)

package DesignPatterns.templatemethod;

public abstract class
MainDataProcess {

   
// Template method
   
public void readProcessSave(){
        readData()
; // Step 1: Read data
       
processData();  // Step 2: Process data
       
SaveData(); // Step 3: Save data to database
   
}

   
// Abstract methods to be implemented by subclasses
   
public abstract void readData();
    public abstract void
processData();

   
// Concrete method with default implementation
   
public void SaveData(){
        System.
out.println("Save Data To DB");
   
}
}

Explanation:

ü  MainDataProcess is an abstract class that defines a template method readProcessSave().

ü  This method outlines the steps required to read, process, and save data.

ü  readData() and processData() are abstract methods that subclasses (ExcelFile and WordFile) must implement based on their specific data sources (Excel or Word files).

2. Concrete Classes (ExcelFile and WordFile)

ExcelFile.java

package DesignPatterns.templatemethod;

public class
ExcelFile extends MainDataProcess {

   
public void readData() {
        System.
out.println("Read Data From - ExcelFile");
   
}

   
public void processData() {
        System.
out.println("Process Daata from -ExcelFile");
   
}

}

WordFile.java

package DesignPatterns.templatemethod;

public class
WordFile extends MainDataProcess {


   
public void readData() {
        System.
out.println("Read Data From - WordFile");
   
}

   
public void processData() {
        System.
out.println("Process Data from -WordFile");
   
}
}

Explanation:

ü  ExcelFile and WordFile extend MainDataProcess and provide specific implementations for readData() and processData() methods.

Each subclass defines how data should be read and processed from Excel and Word files respectively.

3. Client Code (TemplatePattern)

TemplatePattern.java

package DesignPatterns.templatemethod;

public class
TemplatePattern {
   
public static void main(String[] args) {
        MainDataProcess exobject =
new ExcelFile();
       
exobject.readProcessSave();  // Executes ExcelFile's readProcessSave() method

       
System.out.println();

       
MainDataProcess wordObject = new WordFile();
       
wordObject.readProcessSave();  // Executes WordFile's readProcessSave() method

   
}
}

 

Explanation:

ü  TemplatePattern class contains the main() method where instances of ExcelFile and WordFile are created and their readProcessSave() methods are invoked.

 

Execution Flow:

ü  When exobject.readProcessSave() is called, it triggers the template method defined in MainDataProcess.

ü  For ExcelFile, readData() prints "Read Data From - ExcelFile" and processData() prints "Process Data from - ExcelFile".

ü  After processing, saveData() prints "Save Data To DB".

ü  Similarly, wordObject.readProcessSave() invokes WordFile's implementations of readData(), processData(), and saveData().

 

4. Output

When you run the TemplatePattern class, the output will be:




 

Explanation:

ü  The output demonstrates that the template method (readProcessSave()) in MainDataProcess defines the overall process (readData(), processData(), saveData()).

ü  Subclasses (ExcelFile and WordFile) provide specific implementations for reading and processing data while adhering to the structured flow defined in the template method.

 

 

Advantages

·         Code Reuse: The template method defines the structure of an algorithm once in an abstract class and allows subclasses to provide specific implementations for certain steps. This promotes reuse of common code across multiple subclasses.

 

·         Flexibility: Subclasses can override specific steps of the algorithm to customize the behavior without affecting the overall structure defined in the template method.

 

·         Maintenance: Changes to the algorithm can be made centrally in the abstract class, ensuring consistency across all subclasses.

 

Disadvantages

·         Limited Flexibility: Since the template method defines the structure of the algorithm, it can be restrictive if subclasses need drastically different behaviors that cannot fit into the template.

 

·         Complexity: Managing multiple levels of inheritance and ensuring that subclasses adhere to the template method's contract can introduce complexity.

 

When to Use

·         Use the Template Method Pattern when you have a group of algorithms that share a common structure but differ in some steps.

 

·         Use it to avoid code duplication by centralizing common behavior in an abstract class.

  

Conclusion

·        👉  Used to create a group of subclasses that have to execute a similar group of methods.

·        👉 You create an abstract class that contains a method called the template method

·        👉 The template method contains a series of method calls that every subclass object will call

·     👉   The subclass objects can override some of the method calls

 

Comments

Popular posts from this blog

Unveiling the Trinity of Standards, Objects, and Classes

A Guide to Object Generating, Data Types, Parameters and Arguments

Getting Started with Design Patterns - Part 1