The Template Method Pattern is a behavioral design pattern that defines the skeleton of an algorithm in an abstract base class, allowing subclasses to redefine certain steps without altering the overall structure.
In our example, we define an abstract class called CoffeeTemplate containing:
Abstract Methods:boilWater(), addMilk(), addSugar(), and addCoffeePowder(). Subclasses implement these specific steps.
Template Method:prepareCoffee(). This method executes the sequence of steps and is marked final so subclasses cannot alter the overall algorithm.
Java Implementation Breakdown
Here is how the core structure is laid out in code:
// Abstract Template Class
public abstract class CoffeeTemplate {
// Template method defined as final
public final void prepareCoffee() {
boilWater();
addMilk();
addSugar();
addCoffeePowder();
System.out.println("Coffee is ready!\n");
}
public abstract void boilWater();
public abstract void addMilk();
public abstract void addSugar();
public abstract void addCoffeePowder();
}
The concrete classes BruCoffee and NescafeCoffee extend CoffeeTemplate and specify the exact quantities and powder types. The client simply invokes prepareCoffee(), maintaining clean separation of concerns and eliminating code duplication.
Understanding the Problem: Building Different Types of Houses
When building any house—whether a Glass House or a Wooden House—the sequence of construction remains identical:
Build the foundation
Build the pillars
Build the walls
Build the windows
While the overall sequence never changes, the materials used in each step vary. For a wooden house, you use wood coatings and wooden walls. For a glass house, you use glass coatings and glass panels.
The Template Method Solution
Instead of rewriting the construction sequence in every subclass, we define the entire workflow once inside an abstract class called HouseTemplate:
Template Method (buildHouse()): Declared as final so subclasses cannot alter the sequence of construction.
Abstract Primitive Methods:buildFoundation(), buildPillars(), buildWalls(), and buildWindows() are left abstract for subclasses to provide specific material logic.
Java Code Implementation
Here is how the template pattern structure is set up in Java:
// Abstract Template Class
public abstract class HouseTemplate {
// Template method defining the construction sequence
public final void buildHouse() {
buildFoundation();
buildPillars();
buildWalls();
buildWindows();
System.out.println("House is built successfully!\n");
}
public abstract void buildFoundation();
public abstract void buildPillars();
public abstract void buildWalls();
public abstract void buildWindows();
}
Concrete classes such as WoodenHouse and GlassHouse extend HouseTemplate and supply custom logic for building with wood or glass. The client class HousingClient simply calls buildHouse(), keeping client code simple, decoupled, and clean.
The Template Method Pattern is a behavioral design pattern used widely across frameworks and standard libraries. It defines the sequence of an algorithm in a base class method while delegating specific sub-steps to subclasses.
This design promotes fundamental object-oriented principles: it maximizes code reuse, establishes a reliable execution contract, and avoids code duplication across related implementations.
Essential Rules and Key Takeaways
When applying the Template Method pattern in your projects, keep these crucial guidelines in mind:
Make the Template Method final: Always declare the template method with the final keyword so child classes cannot override or break the execution sequence.
Keep Variable Steps abstract: Any step that must be customized by subclasses should be declared abstract in the parent class.
Support Default Behaviors: Steps common to all or most subclasses can have a default concrete implementation in the base class.
Use Hook Methods: Hooks provide optional extension points allowing subclasses to decide whether specific logic runs without modifying the core flow.
The Hollywood Principle: Embody "Don't call us, we'll call you." The high-level abstract class controls the workflow and calls low-level subclass implementations when needed.
When Should You Use It?
Use the Template Method Pattern when:
Multiple classes share nearly identical multi-step algorithms, differing only in specific operations.
You want to control extension points strictly, preventing callers from changing the structural order of operations.
You are creating a framework or library where consumers should customize behavior without altering framework logic.
Every car assembly plant follows a strict, step-by-step assembly process. Regardless of whether a factory manufactures a standard sedan, an SUV, or a luxury sports car, the foundational stages remain unchanged:
Assemble the chassis and skeleton frame
Mount the engine and transmission
Install the wheels and axles
Assemble the vehicle body and paint
While the sequence of assembly operations is identical for all car models, the individual components, parts, and assembly specifics vary significantly between models.
Applying the Template Method Pattern
The Template Method Design Pattern fits this scenario by putting the structural assembly pipeline in a base class and delegating the specific parts to individual car models:
Template Method (buildCar()): Declared as final in the parent class to guarantee that no subclass can alter the chronological sequence of car manufacturing.
Primitive Abstract Steps: Methods like buildSkeleton(), installEngine(), and attachWheels() are left abstract so that specific car models provide their concrete parts.
Java Architecture Blueprint
Here is how the template and its specializations are constructed in Java:
// Abstract Template Class
public abstract class CarTemplate {
// Final template method defining fixed assembly pipeline
public final void buildCar() {
buildSkeleton();
installEngine();
attachWheels();
bodyPaint();
System.out.println("Car manufacturing complete!\n");
}
public abstract void buildSkeleton();
public abstract void installEngine();
public abstract void attachWheels();
public abstract void bodyPaint();
}
By structuring the classes this way, child classes implement custom parts without duplicating the manufacturing workflow logic, keeping your codebase maintainable and strictly organized.
Even though the sequence of preparation steps is universal, the exact amount of sugar, quantity of milk, and brand or type of coffee powder depend entirely on the specific coffee flavor being brewed.
How the Template Method Pattern Solves This
Without a structured pattern, you might find yourself copying and pasting the preparation steps inside every single coffee class. If the sequence changes later, you would have to update multiple files.
The Template Method Design Pattern elegantly solves this problem:
Base Template Class: An abstract class (such as CoffeeTemplate) provides the overarching algorithm in a template method.
Preserving the Flow: The template method calls each step in order and is typically marked final to stop subclasses from reordering the recipe.
Subclass Flexibility: Individual steps are declared as abstract methods so specific subclasses can implement their unique ingredients and measurements.
Key Architectural Takeaways
Applying this pattern guarantees a standardized workflow across all implementations while maintaining low coupling:
Eliminates Redundancy: Shared execution code resides strictly in one parent class.
Consistent Execution: Guarantees that essential steps (like boiling water before serving) are never bypassed.
Extensibility: Introducing a new recipe (such as Cappuccino or Espresso) only requires extending the base template and implementing the missing step methods.
A UML class diagram offers a visual blueprint of how classes collaborate in the Template Method Design Pattern. The structure centers around two key architectural participants:
AbstractClass (Template): Defines abstract primitive operations that concrete subclasses must implement, along with the main template method that orchestrates the execution flow.
ConcreteClass: Extends the abstract class and provides specific implementations for each primitive step without altering the overall algorithm sequence.
Key Structural Elements in UML
When reading or drafting the UML diagram for this pattern, pay close attention to these core components:
Template Method: Declared in the base class, this method defines the algorithmic skeleton by invoking primitive operations in a fixed sequence.
Primitive Operations: Marked as abstract methods (italicized in standard UML notation) in the parent class to mandate subclass implementations.
Inheritance Relationship: Subclasses share an "is-a" relationship (represented by a solid line with a hollow arrow pointing to the base class), inheriting the algorithm framework.
Why the Diagram Matters for Developers
Visualizing the class hierarchy clarifies how inversion of control operates in practice:
Decouples Workflow from Details: The caller deals solely with the abstract contract, remaining oblivious to specific subclass variants.
Guarantees Invariant Behavior: Because the template method remains unified in the parent class, subclasses cannot accidentally bypass essential execution steps.
Streamlines System Maintenance: Introducing a new variant requires only plugging in a new concrete child class into the existing hierarchy.
The Template Design Pattern (also called the Template Method Design Pattern) is categorized as a behavioral design pattern. It defines the skeleton of an algorithm in an abstract base class, delegating the execution of specific steps to subclasses without permitting alterations to the algorithm's overarching flow.
In simpler words, think of a template document or a recipe outline. The sequence of actions is locked in place, but individual details can be tailored to meet distinct business requirements.
Core Concepts and Structure
The architecture of this pattern revolves around two central components:
The Abstract Base Class: Contains the Template Method, which calls individual primitive methods in a specific logical order. It is marked final in Java to prevent subclasses from modifying the algorithm sequence.
Concrete Subclasses: Extend the base class and override the abstract primitive steps to supply specific implementation logic for that variant.
Why Use the Template Method Pattern?
Applying the Template Method pattern offers several major benefits for your application architecture:
Code Reusability: Common workflow logic resides in a single abstract class rather than duplicating boilerplate across multiple classes.
Inversion of Control: Known as the "Hollywood Principle" ("Don't call us, we'll call you"), the parent class controls execution order, calling child implementations when needed.
Controlled Extensibility: You decide precisely where extensions are allowed by declaring only certain methods as abstract or overridable hooks.