Java

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

AspectDetails
Pattern TypeBehavioral Design Pattern
Primary BenefitAlgorithm skeleton reuse, consistent structure
Hook TypesRequired (abstract), Optional (default), Notification
Spring ExamplesJdbcTemplate, 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)
Code
Loading syntax highlighter...
Problems:
  • Bug fixes needed in 15 places
  • Inconsistent error handling
  • New reports copy-pasted more bugs
  • Testing required 15 separate test suites
The fix: Template Method:
JAVA(25 lines)
Code
Loading syntax highlighter...

Mental Model: Template Method Structure

TEXT(33 lines)
Code
Loading syntax highlighter...

🔬 Deep Dive

Pattern 1: Classic Template Method

JAVA(59 lines)
Code
Loading syntax highlighter...

Pattern 2: Hook Types

JAVA(80 lines)
Code
Loading syntax highlighter...

Pattern 3: Functional Template (Lambda-Based)

JAVA(83 lines)
Code
Loading syntax highlighter...

Pattern 4: Spring Template Classes

JAVA(88 lines)
Code
Loading syntax highlighter...

Pattern 5: Custom Spring Template

JAVA(80 lines)
Code
Loading syntax highlighter...

Pattern 6: Template with Strategy

JAVA(90 lines)
Code
Loading syntax highlighter...

⚠️ Common Mistakes

Mistake 1: Forgetting to Make Template Final

JAVA(20 lines)
Code
Loading syntax highlighter...

Mistake 2: Too Many Abstract Methods

JAVA(17 lines)
Code
Loading 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)
Code
Loading syntax highlighter...
Why does the fraud check run for all payments regardless of amount?

✅ Solution:
The bug is a method signature mismatch. The hook method in the base class is:
JAVA
Code
Loading syntax highlighter...

But the subclass method has:

JAVA
Code
Loading syntax highlighter...
This is method overloading, not overriding! The base class requiresFraudCheck() is never overridden - it always returns true. The subclass method is a completely different method that never gets called.
The fix - use @Override to catch errors:
JAVA(8 lines)
Code
Loading syntax highlighter...
Better design - pass context to hooks:
JAVA(28 lines)
Code
Loading syntax highlighter...
The lesson: Always use @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

Task: Create a template for data export with customizable format.
JAVA(6 lines)
Code
Loading syntax highlighter...
✅ Solution:
JAVA(68 lines)
Code
Loading syntax highlighter...

Exercise 2: Hooks Implementation

⭐⭐ Difficulty: Medium | ⏱️ Time: 20 minutes

Task: Add multiple hook types to a notification template.
JAVA(6 lines)
Code
Loading syntax highlighter...
✅ Solution:
JAVA(87 lines)
Code
Loading syntax highlighter...

Exercise 3: Functional Template

⭐⭐ Difficulty: Medium | ⏱️ Time: 20 minutes

Task: Convert a class-based template to functional style.
JAVA(13 lines)
Code
Loading syntax highlighter...
✅ Solution:
JAVA(81 lines)
Code
Loading syntax highlighter...

Exercise 4: Spring-Style Template

⭐⭐⭐ Difficulty: Medium-Hard | ⏱️ Time: 25 minutes

Task: Create a custom template for API calls with retry and circuit breaker.
JAVA(10 lines)
Code
Loading syntax highlighter...
✅ Solution:
JAVA(97 lines)
Code
Loading syntax highlighter...

Exercise 5: Template with Strategy Combination

⭐⭐⭐⭐ Difficulty: Hard | ⏱️ Time: 30 minutes

Task: Create a report generation template that combines with formatting and delivery strategies.
JAVA(10 lines)
Code
Loading syntax highlighter...
✅ Solution:
JAVA(153 lines)
Code
Loading syntax highlighter...

🎤 Interview Questions

Q1: Template Method vs Strategy Pattern?

Answer:
  • 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?

Answer: Hooks are optional methods with default (often empty) implementations:
  • 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

ConceptUse When
Template MethodShared algorithm structure, variable steps
Required HooksStep MUST be customized
Optional HooksStep CAN be customized
Functional TemplatePrefer composition over inheritance
Spring TemplatesDatabase, HTTP, transaction operations

📅 Review Schedule for This Article

DayTaskTime
Day 1Review Template Method structure diagram5 min
Day 3Redo Exercise 1 (Basic Template Method)15 min
Day 7Answer interview questions without looking10 min
Day 14Redo Debug This (Broken Hook)15 min
Day 30Identify one duplicated algorithm in your codebase to template20 min

Next: [Part 14: Exception Hierarchy Design]