Template Method Pattern – Head First Approach
Reusable Algorithms with Flexible Steps

As a continuous learner, I’m always exploring new technologies and best practices to enhance my skills in software development. I enjoy tackling complex coding challenges, whether it's optimizing performance, implementing new features, or debugging intricate issues.
The Template Method Pattern is a behavioral design pattern that defines the skeleton of an algorithm in a method, allowing subclasses to redefine certain steps without changing the overall structure of the algorithm.
What is the Template Method Pattern?
Definition: The Template Method Pattern defines the basic structure of an algorithm in a superclass but lets subclasses modify specific steps without altering the algorithm’s core logic.
This pattern promotes code reuse while allowing flexibility where needed, making it easier to customize specific steps without rewriting the entire algorithm.
Problem Scenario
Consider an application where you want to implement a coffee brewing process. The steps for brewing are mostly the same: boiling water, brewing coffee, and pouring it into a cup. However, different kinds of coffee may require adding unique condiments like milk or sugar. Without the Template Method Pattern, you'd end up duplicating most of the brewing logic. This pattern allows you to centralize the common steps while giving flexibility for customization.
Using the Template Method Pattern
The Head First Design Patterns book offers an example using a beverage preparation process, where subclasses can override specific steps to create unique drinks.
Step 1: Create the Abstract Class with the Template Method
The abstract class contains the template method, defining the steps of the algorithm.
public abstract class CaffeineBeverage {
// Template method
public final void prepareRecipe() {
boilWater();
brew();
pourInCup();
addCondiments();
}
abstract void brew();
abstract void addCondiments();
public void boilWater() {
System.out.println("Boiling water");
}
public void pourInCup() {
System.out.println("Pouring into cup");
}
}
Step 2: Create Concrete Classes
Each subclass provides its own implementation for specific steps, like brewing the coffee or adding condiments.
public class Coffee extends CaffeineBeverage {
public void brew() {
System.out.println("Dripping coffee through filter");
}
public void addCondiments() {
System.out.println("Adding sugar and milk");
}
}
public class Tea extends CaffeineBeverage {
public void brew() {
System.out.println("Steeping the tea");
}
public void addCondiments() {
System.out.println("Adding lemon");
}
}
Step 3: Use the Template Method in Client Code
The client uses the template method to prepare specific beverages.
public class BeverageTest {
public static void main(String[] args) {
CaffeineBeverage coffee = new Coffee();
coffee.prepareRecipe();
CaffeineBeverage tea = new Tea();
tea.prepareRecipe();
}
}
Output:
Boiling water
Dripping coffee through filter
Pouring into cup
Adding sugar and milk
Boiling water
Steeping the tea
Pouring into cup
Adding lemon
In this example, the prepareRecipe() method follows a fixed sequence of steps, but each subclass can customize the brewing and condiment-adding steps.
Expanding the Template Method Pattern
Adding Optional Hooks
You can further expand the pattern by using optional "hooks" that subclasses can override. Hooks are methods defined in the abstract class that provide optional functionality for subclasses. They can add or skip specific steps.
public abstract class CaffeineBeverageWithHook {
public final void prepareRecipe() {
boilWater();
brew();
pourInCup();
if (customerWantsCondiments()) {
addCondiments();
}
}
abstract void brew();
abstract void addCondiments();
public void boilWater() {
System.out.println("Boiling water");
}
public void pourInCup() {
System.out.println("Pouring into cup");
}
// Hook method
boolean customerWantsCondiments() {
return true;
}
}
By overriding the customerWantsCondiments() method, subclasses can decide whether to add condiments.
When to Use the Template Method Pattern
Shared behavior: If you have algorithms that share a common structure but differ in certain steps, the Template Method Pattern helps avoid code duplication.
Extensibility: When you want to allow subclasses to extend certain parts of an algorithm without affecting its overall structure.
Code reuse: You can centralize shared steps of the algorithm in a base class, allowing subclasses to reuse and customize only what they need.
Bullet Points
The Template Method Pattern defines the structure of an algorithm, with some steps left to be implemented by subclasses.
It promotes code reuse by placing shared logic in the abstract class while allowing flexibility where needed.
It can include "hooks" for optional behavior that subclasses can override.
It’s ideal for situations where you have multiple variations of the same algorithm.
Conclusion
The Template Method Pattern is a powerful tool for creating reusable algorithms with flexible steps. By defining the structure in a base class and leaving certain steps to be implemented by subclasses, it strikes a balance between code reuse and extensibility.




