Template Method Pattern
Template Method defines the skeleton of an algorithm, letting subclasses override specific steps. Combined with hook methods, it provides powerful extension points while enforcing consistent structure. This article covers classic templates, functional alternatives, and Spring's template classes.
📋 At a Glance
| Aspect | Details |
|---|---|
| Pattern Type | Behavioral Design Pattern |
| Primary Benefit | Algorithm skeleton reuse, consistent structure |
| Hook Types | Required (abstract), Optional (default), Notification |
| Spring Examples | JdbcTemplate, RestTemplate, TransactionTemplate |
🎯 What You'll Learn
- Template Method Pattern with abstract and hook methods
- Functional templates with lambdas
- Spring templates (JdbcTemplate, RestTemplate)
- Hook patterns for extensibility
- When to use vs composition alternatives
Production Story: The Report Generator
A reporting system had copy-pasted code across 15 report types:
JAVA(25 lines)CodeLoading syntax highlighter...
- Bug fixes needed in 15 places
- Inconsistent error handling
- New reports copy-pasted more bugs
- Testing required 15 separate test suites
JAVA(25 lines)CodeLoading syntax highlighter...
Mental Model: Template Method Structure
TEXT(33 lines)CodeLoading syntax highlighter...
🔬 Deep Dive
Pattern 1: Classic Template Method
JAVA(59 lines)CodeLoading syntax highlighter...
Pattern 2: Hook Types
JAVA(80 lines)CodeLoading syntax highlighter...
Pattern 3: Functional Template (Lambda-Based)
JAVA(83 lines)CodeLoading syntax highlighter...
Pattern 4: Spring Template Classes
JAVA(88 lines)CodeLoading syntax highlighter...
Pattern 5: Custom Spring Template
JAVA(80 lines)CodeLoading syntax highlighter...
Pattern 6: Template with Strategy
JAVA(90 lines)CodeLoading syntax highlighter...
⚠️ Common Mistakes
Mistake 1: Forgetting to Make Template Final
JAVA(20 lines)CodeLoading syntax highlighter...
Mistake 2: Too Many Abstract Methods
JAVA(17 lines)CodeLoading syntax highlighter...
🐛 Debug This: The Broken Hook
A developer reports: "Our payment template should skip fraud check for PayPal payments under $500, but ALL payments are getting fraud checked!"
JAVA(50 lines)CodeLoading syntax highlighter...
JAVACodeLoading syntax highlighter...
But the subclass method has:
JAVACodeLoading syntax highlighter...
requiresFraudCheck() is never overridden - it always returns true. The subclass method is a completely different method that never gets called.JAVA(8 lines)CodeLoading syntax highlighter...
JAVA(28 lines)CodeLoading syntax highlighter...
@Override annotation - it causes a compile error if the signature doesn't match. Design hooks with necessary context parameters.💻 Exercises
Exercise 1: Basic Template Method
⭐ Difficulty: Easy | ⏱️ Time: 15 minutes
JAVA(6 lines)CodeLoading syntax highlighter...
JAVA(68 lines)CodeLoading syntax highlighter...
Exercise 2: Hooks Implementation
⭐⭐ Difficulty: Medium | ⏱️ Time: 20 minutes
JAVA(6 lines)CodeLoading syntax highlighter...
JAVA(87 lines)CodeLoading syntax highlighter...
Exercise 3: Functional Template
⭐⭐ Difficulty: Medium | ⏱️ Time: 20 minutes
JAVA(13 lines)CodeLoading syntax highlighter...
JAVA(81 lines)CodeLoading syntax highlighter...
Exercise 4: Spring-Style Template
⭐⭐⭐ Difficulty: Medium-Hard | ⏱️ Time: 25 minutes
JAVA(10 lines)CodeLoading syntax highlighter...
JAVA(97 lines)CodeLoading syntax highlighter...
Exercise 5: Template with Strategy Combination
⭐⭐⭐⭐ Difficulty: Hard | ⏱️ Time: 30 minutes
JAVA(10 lines)CodeLoading syntax highlighter...
JAVA(153 lines)CodeLoading syntax highlighter...
🎤 Interview Questions
Q1: Template Method vs Strategy Pattern?
- Template Method: Uses inheritance, defines algorithm skeleton with variable steps
- Strategy: Uses composition, entire algorithm is interchangeable
Template Method: "same algorithm, different steps" Strategy: "different algorithms entirely"
Q2: What are hooks in Template Method?
- Required hooks (abstract): Must be implemented
- Optional hooks: Default implementation, can override
- Notification hooks: For observation (beforeX, afterX)
- Conditional hooks: Control flow (shouldDoX returns boolean)
📝 Summary
| Concept | Use When |
|---|---|
| Template Method | Shared algorithm structure, variable steps |
| Required Hooks | Step MUST be customized |
| Optional Hooks | Step CAN be customized |
| Functional Template | Prefer composition over inheritance |
| Spring Templates | Database, HTTP, transaction operations |
📅 Review Schedule for This Article
| Day | Task | Time |
|---|---|---|
| Day 1 | Review Template Method structure diagram | 5 min |
| Day 3 | Redo Exercise 1 (Basic Template Method) | 15 min |
| Day 7 | Answer interview questions without looking | 10 min |
| Day 14 | Redo Debug This (Broken Hook) | 15 min |
| Day 30 | Identify one duplicated algorithm in your codebase to template | 20 min |