Template Method Pattern
Template Method Pattern
Section titled “Template Method Pattern”The Template Method Pattern is one of the most fundamental behavioral design patterns that defines the skeleton of an algorithm in a base class, letting subclasses override specific steps without changing the algorithm’s structure. Understanding the Template Method Pattern is essential for building flexible, maintainable software systems.
Why Template Method Pattern?
Section titled “Why Template Method Pattern?”Imagine you’re making different types of beverages - tea and coffee. The process is similar: boil water, brew, pour, add condiments. But “brew” means steeping tea leaves for tea, and filtering coffee for coffee. The Template Method Pattern lets you define this common process once, with specific steps filled in by subclasses!
The Template Method Pattern defines the skeleton of an algorithm in a base class method, deferring some steps to subclasses. It lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.
What’s the Use of Template Method Pattern?
Section titled “What’s the Use of Template Method Pattern?”The Template Method Pattern is useful when:
- You have a common algorithm structure - Same steps, different details
- You want to avoid code duplication - Common code in base class
- You need to control extension points - Subclasses can only customize certain steps
- You want to enforce algorithm structure - Subclasses can’t change the order
- You have invariant steps - Some steps must always happen
What Happens If We Don’t Use Template Method Pattern?
Section titled “What Happens If We Don’t Use Template Method Pattern?”Without the Template Method Pattern, you might:
- Duplicate code - Same algorithm structure in multiple places
- Inconsistent implementations - Different classes implement differently
- Hard to maintain - Changes needed in multiple places
- No control over extensions - Subclasses can change everything
- Violate DRY - Don’t Repeat Yourself principle violated
Simple Example: The Beverage Maker
Section titled “Simple Example: The Beverage Maker”Let’s start with a super simple example that anyone can understand!
Visual Representation
Section titled “Visual Representation”Algorithm Flow
Section titled “Algorithm Flow”Here’s how the template method works - same structure, different implementations:
sequenceDiagram
participant Client
participant Tea
participant Coffee
participant BaseClass as Beverage (Base)
Client->>Tea: prepare_recipe()
activate Tea
Tea->>BaseClass: boil_water()
BaseClass-->>Tea: Water boiled
Tea->>Tea: brew() [steep tea]
Note right of Tea: Subclass implementation
Tea->>BaseClass: pour_in_cup()
BaseClass-->>Tea: Poured
Tea->>Tea: add_condiments() [add lemon]
Note right of Tea: Subclass implementation
Tea-->>Client: Tea ready!
deactivate Tea
Client->>Coffee: prepare_recipe()
activate Coffee
Coffee->>BaseClass: boil_water()
BaseClass-->>Coffee: Water boiled
Coffee->>Coffee: brew() [drip coffee]
Note right of Coffee: Different implementation
Coffee->>BaseClass: pour_in_cup()
BaseClass-->>Coffee: Poured
Coffee->>Coffee: add_condiments() [add milk]
Note right of Coffee: Different implementation
Coffee-->>Client: Coffee ready!
deactivate Coffee
The Problem
Section titled “The Problem”You’re building a beverage maker that can make tea and coffee. Without Template Method Pattern:
Problems:
- Code duplication - Same steps copied everywhere
- Maintenance nightmare - Change in multiple places
- No structure enforcement - Easy to forget steps
- Violates DRY principle
The Solution: Template Method Pattern
Section titled “The Solution: Template Method Pattern”Class Structure
Section titled “Class Structure”classDiagram
class Beverage {
<<abstract>>
+prepare_recipe() void
+boil_water() void
#brew()* void
+pour_in_cup() void
#add_condiments()* void
}
class Tea {
#brew() void
#add_condiments() void
}
class Coffee {
#brew() void
#add_condiments() void
}
class HotChocolate {
#brew() void
#add_condiments() void
}
Beverage <|-- Tea : extends
Beverage <|-- Coffee : extends
Beverage <|-- HotChocolate : extends
note for Beverage "Template method: prepare_recipe()\nConcrete: boil_water(), pour_in_cup()\nAbstract: brew(), add_condiments()"
Real-World Software Example: Data Mining Pipeline
Section titled “Real-World Software Example: Data Mining Pipeline”Now let’s see a realistic software example - a data mining pipeline that processes data from different sources.
The Problem
Section titled “The Problem”You’re building a data processing system that needs to handle CSV files, JSON APIs, and databases. The process is similar: open connection, extract data, transform, analyze, generate report, close connection. Without Template Method:
Problems:
- Common steps duplicated across all miners
- Changes need to be made in multiple places
- No enforcement of the mining process
The Solution: Template Method Pattern
Section titled “The Solution: Template Method Pattern”Class Structure
Section titled “Class Structure”classDiagram
class DataMiner {
<<abstract>>
+mine(source) void
#open_source(source)* void
#extract_data()* List
+transform_data(data) List
+analyze_data(data) Report
+generate_report(analysis) void
#close_source()* void
+hook_before_analysis() void
}
class CSVDataMiner {
#open_source(source) void
#extract_data() List
#close_source() void
}
class JSONAPIMiner {
#open_source(source) void
#extract_data() List
#close_source() void
}
class DatabaseMiner {
#open_source(source) void
#extract_data() List
#close_source() void
+hook_before_analysis() void
}
DataMiner <|-- CSVDataMiner : extends
DataMiner <|-- JSONAPIMiner : extends
DataMiner <|-- DatabaseMiner : extends
note for DataMiner "Template method: mine()\nAbstract: open, extract, close\nConcrete: transform, analyze, report\nHook: hook_before_analysis()"
Template Method Pattern Variants
Section titled “Template Method Pattern Variants”1. With Hooks
Section titled “1. With Hooks”Hooks are optional methods that can be overridden:
Hooks allow:
- Optional customization without forcing implementation
- Conditional execution of steps
- Default behavior that can be changed
2. Hollywood Principle
Section titled “2. Hollywood Principle”“Don’t call us, we’ll call you” - Base class calls subclass methods:
sequenceDiagram
participant Client
participant BaseClass
participant SubClass
Client->>BaseClass: templateMethod()
BaseClass->>BaseClass: step1()
BaseClass->>SubClass: abstractStep2()
Note right of SubClass: Subclass method called by base
SubClass-->>BaseClass: return
BaseClass->>BaseClass: step3()
BaseClass-->>Client: done
When to Use Template Method Pattern?
Section titled “When to Use Template Method Pattern?”Use Template Method Pattern when:
✅ Common algorithm structure - Same steps, different implementations
✅ Code duplication - Same structure repeated in multiple classes
✅ Control extension points - Only certain steps can be customized
✅ Enforce invariant steps - Some steps must always happen
✅ Hollywood Principle - Framework calls user code
When NOT to Use Template Method Pattern?
Section titled “When NOT to Use Template Method Pattern?”Don’t use Template Method Pattern when:
❌ Algorithms are completely different - No common structure
❌ All steps need customization - Use Strategy instead
❌ Inheritance isn’t appropriate - Use composition
❌ Simple cases - Just a few steps, no duplication
Common Mistakes to Avoid
Section titled “Common Mistakes to Avoid”Mistake 1: Making Template Method Overridable
Section titled “Mistake 1: Making Template Method Overridable”Mistake 2: Too Many Abstract Methods
Section titled “Mistake 2: Too Many Abstract Methods”Mistake 3: Not Using Hooks for Optional Steps
Section titled “Mistake 3: Not Using Hooks for Optional Steps”Benefits of Template Method Pattern
Section titled “Benefits of Template Method Pattern”- Code Reuse - Common code in base class
- Algorithm Structure - Can’t be changed by subclasses
- Single Point of Change - Fix bugs once
- Controlled Extension - Only specific steps customizable
- Inversion of Control - Hollywood Principle
- DRY Principle - Don’t Repeat Yourself
Revision: Quick Catch-Up
Section titled “Revision: Quick Catch-Up”What is Template Method Pattern?
Section titled “What is Template Method Pattern?”Template Method Pattern is a behavioral design pattern that defines the skeleton of an algorithm in a base class method, letting subclasses override specific steps without changing the algorithm’s structure.
Why Use It?
Section titled “Why Use It?”- ✅ Code reuse - Common steps in base class
- ✅ Algorithm structure - Fixed, can’t be changed
- ✅ Controlled extension - Only specific steps customizable
- ✅ DRY principle - No duplication
- ✅ Hollywood Principle - “Don’t call us, we’ll call you”
How It Works?
Section titled “How It Works?”- Create abstract base class - With template method
- Define template method - The algorithm skeleton
- Add concrete methods - Common implementations
- Add abstract methods - Customization points
- Add hooks - Optional customization
- Create subclasses - Implement abstract methods
Key Components
Section titled “Key Components”Abstract Class (Template Method)├── template_method() → defines algorithm├── concrete_step() → common implementation├── abstract_step() → subclass implements└── hook() → optional overrideSimple Example
Section titled “Simple Example”class Beverage(ABC): def prepare_recipe(self): # Template method self.boil_water() # Concrete self.brew() # Abstract self.pour_in_cup() # Concrete self.add_condiments() # Abstract
def boil_water(self): print("Boiling water")
@abstractmethod def brew(self): pass
@abstractmethod def add_condiments(self): passWhen to Use?
Section titled “When to Use?”✅ Common algorithm structure
✅ Code duplication in algorithm
✅ Need to control extension points
✅ Invariant steps must happen
✅ Framework development
When NOT to Use?
Section titled “When NOT to Use?”❌ Completely different algorithms
❌ All steps need customization
❌ Simple cases with no duplication
Key Takeaways
Section titled “Key Takeaways”- Template Method = Algorithm skeleton in base class
- Abstract methods = Customization points
- Concrete methods = Common implementation
- Hooks = Optional customization
- Hollywood Principle = Base calls subclass methods
Interview Focus: Template Method Pattern
Section titled “Interview Focus: Template Method Pattern”Key Points to Remember
Section titled “Key Points to Remember”1. Core Concept
Section titled “1. Core Concept”What to say:
“Template Method Pattern is a behavioral design pattern that defines the skeleton of an algorithm in a base class method, letting subclasses override specific steps without changing the algorithm’s structure. It promotes code reuse and enforces a consistent algorithm structure.”
Why it matters:
- Shows you understand the fundamental purpose
- Demonstrates knowledge of inheritance-based patterns
- Indicates you can explain concepts clearly
2. Template Method vs Strategy Pattern
Section titled “2. Template Method vs Strategy Pattern”Must discuss:
- Template Method - Uses inheritance, algorithm structure fixed
- Strategy - Uses composition, entire algorithm swapped
- Key difference - Template customizes steps, Strategy replaces algorithm
Example to give:
“Template Method is like a form with blanks to fill in - the structure is fixed, you just provide specific content. Strategy is like choosing a completely different form. Template Method changes parts of an algorithm; Strategy changes the entire algorithm.”
3. Hollywood Principle
Section titled “3. Hollywood Principle”Must explain:
- “Don’t call us, we’ll call you”
- Base class calls subclass methods (inversion of control)
- Framework pattern - framework controls flow
Example to give:
“In Template Method, the base class controls when subclass methods are called - this is the Hollywood Principle. The subclass doesn’t call the base class to get things done; instead, the base class calls down to the subclass when it needs specific implementation.”
4. Benefits and Trade-offs
Section titled “4. Benefits and Trade-offs”Benefits to mention:
- Code reuse - Common code in base class
- Consistent structure - Algorithm can’t be altered
- Single point of change - Fix bugs once
- Controlled extension - Limited customization points
- DRY principle - No duplication
Trade-offs to acknowledge:
- Inheritance limitation - Java single inheritance
- Harder to understand - Need to trace through hierarchy
- Tight coupling - Subclasses tied to base class structure
- Fragile base class - Changes to base affect all
5. Common Interview Questions
Section titled “5. Common Interview Questions”Q: “When would you use Template Method over Strategy?”
A:
“I’d use Template Method when I have a fixed algorithm structure with specific steps that vary. For example, a data processing pipeline where opening, transforming, and closing are always the same, but extracting data varies by source. I’d use Strategy when I want to swap the entire algorithm, like different sorting algorithms that have completely different approaches.”
Q: “What are hooks in Template Method?”
A:
“Hooks are methods with default (usually empty) implementations that subclasses CAN override but don’t have to. Unlike abstract methods which MUST be overridden, hooks are optional. They provide additional customization points without forcing implementation. For example, a hook before saving that’s empty by default but can add validation.”
Q: “How does Template Method relate to SOLID principles?”
A:
“Template Method supports Open/Closed Principle - the algorithm structure is closed for modification but open for extension via abstract methods. It can violate Single Responsibility if the base class does too much. It demonstrates Dependency Inversion at the method level - the high-level algorithm depends on abstractions (abstract methods), not concrete implementations.”
Interview Checklist
Section titled “Interview Checklist”Before your interview, make sure you can:
- Define Template Method Pattern clearly
- Explain the difference from Strategy Pattern
- Describe the Hollywood Principle
- Implement Template Method from scratch
- List benefits and trade-offs
- Explain hooks vs abstract methods
- Give 2-3 real-world examples
- Discuss when NOT to use it
- Connect to SOLID principles
Remember: Template Method Pattern is about defining the skeleton of an algorithm - let subclasses fill in the details without changing the structure! 📋