Tutorials Design Patterns Mastery
Template Method: Defining skeleton algorithms
On this page
The Template Method Pattern
The Template Method defines the skeleton of an algorithm in an operation, deferring some steps to subclasses. It lets subclasses redefine certain steps of an algorithm without changing the algorithm's overall structure.
1. Scenario: Data Export
All exports follow the same pattern: Open Connection -> Format Data -> Close Connection. The Base class defines the structural flow; the child classes only implement the "Formatting" part.
public abstract class DataExporter
{
// THE TEMPLATE METHOD (sealed to prevent core logic overrides)
public void Export()
{
Connect();
FormatData();
Disconnect();
}
protected abstract void FormatData(); // HOOK for subclasses
}
public class ExcelExporter : DataExporter
{
protected override void FormatData() => Console.WriteLine("Formatting as XLSX...");
}
2. "Hollywood Principle": Don't call us, we'll call you.
The high-level base class controls the flow. It "calls" the low-level subclasses at the appropriate moments. This prevents duplicated "Boilerplate" code across your application.
4. Interview Mastery
Q: "When should I use Template Method vs Strategy?"
Architect Answer: "The choice is between **Inheritance** and **Composition**. Use **Template Method** (Inheritance) when you have a large amount of shared, unchanging code and you only want subclasses to fill in small gaps. Use **Strategy** (Composition) when the entire algorithm needs to be replaced or if you need to switch logic dynamically at runtime without restarting the application."