Template Method Pattern in Java: Definition and Example
Template Method Pattern in Java is a design pattern that defines the skeleton of an algorithm in a method, deferring some steps to subclasses. It lets subclasses redefine certain steps without changing the overall algorithm structure.How It Works
Imagine you are baking a cake. The recipe has fixed steps like mixing ingredients, baking, and cooling. However, the flavor or decoration can change depending on the cake type. The Template Method Pattern works similarly by defining a general algorithm structure in a base class, while allowing subclasses to customize specific steps.
In Java, this means you create an abstract class with a method called the template method. This method calls other methods, some of which are abstract or have default behavior. Subclasses then provide their own versions of these methods to customize the process without changing the main algorithm.
Example
This example shows a base class defining a template method for making a beverage. Subclasses customize the steps for tea and coffee.
abstract class Beverage { // Template method public final void prepareRecipe() { boilWater(); brew(); pourInCup(); addCondiments(); } private void boilWater() { System.out.println("Boiling water"); } // Steps to be customized by subclasses protected abstract void brew(); protected abstract void addCondiments(); private void pourInCup() { System.out.println("Pouring into cup"); } } class Tea extends Beverage { @Override protected void brew() { System.out.println("Steeping the tea leaves"); } @Override protected void addCondiments() { System.out.println("Adding lemon"); } } class Coffee extends Beverage { @Override protected void brew() { System.out.println("Dripping coffee through filter"); } @Override protected void addCondiments() { System.out.println("Adding sugar and milk"); } } public class Main { public static void main(String[] args) { Beverage tea = new Tea(); tea.prepareRecipe(); System.out.println(); Beverage coffee = new Coffee(); coffee.prepareRecipe(); } }
When to Use
Use the Template Method Pattern when you have an algorithm with fixed steps but want to allow subclasses to change some parts without altering the overall process. It helps avoid code duplication and keeps the algorithm structure clear.
Real-world examples include frameworks where the main flow is fixed but specific behaviors vary, like game engines defining game loops or UI toolkits defining rendering steps.
Key Points
- The template method defines the algorithm's skeleton in a base class.
- Subclasses override specific steps without changing the algorithm's structure.
- It promotes code reuse and enforces a consistent process.
- Helps separate invariant parts of an algorithm from variant parts.