Behavioral Design Pattern

Template Method Design Pattern in Java

Define an algorithm skeleton while allowing subclasses to customize selected steps.

In this lesson: Template Method keeps the overall workflow in a base class and delegates variable steps to subclasses.

Overview

Template Method is useful when its recurring design problem appears in a real application. It keeps the relevant responsibilities organized while allowing surrounding code to depend on clear abstractions.

Implementation

abstract class ReportExporter { public final void export() { load(); format(); save(); } protected abstract void load(); protected abstract void format(); protected void save() { System.out.println("Saved"); } }
final class PdfExporter extends ReportExporter { protected void load() { System.out.println("Load data"); } protected void format() { System.out.println("Format PDF"); } }
new PdfExporter().export();

When should you use it?

Use Template Method when several workflows share the same order of steps but differ in one or more implementation details.

Next step: Continue with the Design Patterns course and explore the next pattern.