Understanding the Template Method Design Pattern with Java Examples
This article explains the Template Method design pattern, illustrating its structure with Java drink‑making examples, discussing hook methods, and showing real‑world usages in JDK’s Comparable and Spring’s ApplicationContext, while highlighting advantages, drawbacks, and practical scenarios.
Introduction
Template Method is a behavioral design pattern that defines the skeleton of an algorithm in a superclass while allowing subclasses to override specific steps without changing the overall structure.
Scenario Example
Using a beverage shop analogy, the article first shows a naive interface‑based design and then refactors it into an abstract class Drinks with a final method makingDrinks() that outlines the fixed steps (boil water, brew, pour, add condiments). The invariant steps are implemented in the abstract class, while the variable steps are declared abstract for subclasses.
public
abstract
class
Drinks
{
void
boilWater
()
{
System.out.println(
"将水煮沸"
);
}
abstract
void
brew
()
;
void
pourInCup
()
{
System.out.println(
"倒入杯子"
);
}
abstract
void
addCondiments
()
;
public
final
void
makingDrinks
()
{
//热水
boilWater();
//冲泡
brew();
//倒进杯子
pourInCup();
//加料
addCondiments();
}
}Concrete subclasses Tea and Coffee extend Drinks and implement the abstract methods to provide specific brewing and condiment logic.
public
class
Tea
extends
Drinks
{
@Override
void
brew
()
{
System.out.println(
"冲茶叶"
);
}
@Override
void
addCondiments
()
{
System.out.println(
"加柠檬片"
);
}
} public
class
Coffee
extends
Drinks
{
@Override
void
brew
()
{
System.out.println(
"冲咖啡粉"
);
}
@Override
void
addCondiments
()
{
System.out.println(
"加奶加糖"
);
}
}A main method demonstrates creating Coffee and Tea objects and invoking makingDrinks() to see the template in action.
public
static
void
main
(String[] args)
{
Drinks coffee =
new
Coffee();
coffee.makingDrinks();
System.out.println();
Drinks tea =
new
Tea();
tea.makingDrinks();
}Hook Method
The article introduces a hook method customerLike() that can be overridden by subclasses to decide whether to add condiments, demonstrating how optional steps can be controlled.
public
abstract
class
Drinks
{
...
public
final
void
makingDrinks
()
{
boilWater();
brew();
pourInCup();
//如果顾客需要,才加料
if
(customerLike()) {
addCondiments();
}
}
//默认实现,返回 true
boolean
customerLike
()
{
return
true
;
}
}Real‑World Uses
JDK Comparable
Implementing Comparable requires defining compareTo() , which is called by Collections.sort() or Arrays.sort() . The sorting algorithm is a template method that invokes the user‑provided compareTo for each comparison.
public
int
compareTo
(Object o)
{
Coffee coffee = (Coffee)o;
if(this.price < coffee.price)
return
-1;
else if(this.price == coffee.price)
return
0;
else
return
1;
}Spring ApplicationContext
Spring’s AbstractApplicationContext.refresh() method is a classic template method. It defines the overall container startup workflow while delegating specific steps (e.g., getBeanFactory() , refreshBeanFactory() ) to subclasses and providing hook points such as postProcessBeanFactory() .
public
abstract
class
AbstractApplicationContext
extends
DefaultResourceLoader
{
@Override
public
void
refresh
()
{
synchronized(this.startupShutdownMonitor){
prepareRefresh();
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
prepareBeanFactory(beanFactory);
postProcessBeanFactory(beanFactory);
// … other steps …
finishRefresh();
}
}
protected
void
postProcessBeanFactory
(ConfigurableListableBeanFactory beanFactory){ }
}Summary
Advantages: encapsulates invariant parts, promotes code reuse, and centralizes algorithm control in the superclass.
Disadvantages: each variation requires a new subclass, potentially increasing class count and system complexity.
When to use: multiple subclasses share a common algorithm structure, or a complex method benefits from being broken into a fixed template with customizable steps.
Full-Stack Internet Architecture
Introducing full-stack Internet architecture technologies centered on Java
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.