← Back to Advanced Java Course | Chapter 6: Design Patterns | Lesson 13 of 14

Java Template Method Pattern

The Template Method pattern defines the overall skeleton of an algorithm in a base class, deferring some individual steps to subclasses that override just those steps without changing the algorithm's structure.

What is the Template Method Pattern?

The Template Method pattern defines the overall skeleton of an algorithm in a base class method, deferring some of its individual steps to subclasses, which override just those steps without changing the algorithm's overall structure.

Example: What is the Template Method Pattern?

java
public class Main {
	static abstract class Recipe {
		final void make() { // skeleton
			boilWater();
			addMainIngredient();
		}
		void boilWater() { System.out.println("Boiling water"); }
		abstract void addMainIngredient();
	}
	static class Tea extends Recipe {
		void addMainIngredient() { System.out.println("Adding tea leaves"); }
	}
	public static void main(String[] args) {
		new Tea().make();
	}
}

Defining the Algorithm Skeleton

The template method is typically marked final so subclasses can't alter the overall sequence, only their individual implementations, keeping the algorithm's shape consistent across every subclass.

Example: Defining the Algorithm Skeleton

java
public class Main {
	static abstract class Recipe {
		final void make() { step1(); step2(); } // final -- subclasses can't reorder this
		void step1() { System.out.println("Step 1"); }
		abstract void step2();
	}
	static class Custom extends Recipe {
		void step2() { System.out.println("Custom step 2"); }
	}
	public static void main(String[] args) {
		new Custom().make();
	}
}

Overriding Specific Steps

Steps declared abstract in the base class must be implemented by every subclass, letting each subclass customize exactly those parts of the algorithm while reusing the shared structure and any concrete steps unchanged.

Example: Overriding Specific Steps

java
public class Main {
	static abstract class Report {
		final void generate() { header(); body(); }
		void header() { System.out.println("Header"); }
		abstract void body(); // must be implemented by every subclass
	}
	static class SalesReport extends Report {
		void body() { System.out.println("Sales data"); }
	}
	public static void main(String[] args) {
		new SalesReport().generate();
	}
}

Hook Methods

A hook method has a default implementation in the base class that a subclass can optionally override to influence the template's behavior, such as skipping an optional step, without being required to override it.

Example: Hook Methods

java
public class Main {
	static abstract class Recipe {
		final void make() {
			step1();
			if (wantsExtra()) extra(); // optional hook
		}
		void step1() { System.out.println("Step 1"); }
		boolean wantsExtra() { return false; } // default, overridable
		void extra() { System.out.println("Extra step"); }
	}
	static class Custom extends Recipe {
		boolean wantsExtra() { return true; }
	}
	public static void main(String[] args) {
		new Custom().make();
	}
}

Template Method vs Strategy

Template Method uses inheritance, with a subclass overriding specific steps of a fixed algorithm defined in a base class, while Strategy uses composition, swapping in an entirely different algorithm object at runtime instead.

Example: Template Method vs Strategy

java
public class Main {
	static abstract class TemplateExample { // inheritance -- subclass overrides one step
		final void run() { System.out.println("Fixed structure, step overridden: " + step()); }
		abstract String step();
	}
	interface StrategyExample { String algorithm(); } // composition -- swap the whole algorithm object
	public static void main(String[] args) {
		new TemplateExample() { String step() { return "custom"; } }.run();
		StrategyExample strategy = () -> "different algorithm";
		System.out.println(strategy.algorithm());
	}
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.