Showing posts with label Template Method Pattern. Show all posts
Showing posts with label Template Method Pattern. Show all posts

Monday, 9 December 2013

Template Design pattern or Template Method Design pattern - Implementation [Coffee]

Enjoying Java & Design Pattern Tutorials?

Subscribe to Ram N Java for simplified programming guides, architecture patterns, and practical code walkthroughs!

🔔 Subscribe to Ram N Java

What is the Template Method Design Pattern?

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.

Think of making coffee: every coffee recipe follows a standard sequence — boiling water, brewing/adding coffee powder, adding milk, and adding sugar. While the steps are identical, the exact ingredients and quantities differ depending on whether you are preparing Bru Coffee or Nescafé.

The Real-World Coffee Preparation Analogy

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.

Related Tutorials from Ram N Java


Click here to watch in Youtube : https://www.youtube.com/watch?v=q02WKTGTW_0

Click the below Image to Enlarge
Template Design pattern or Template Method Design pattern - Implementation [Coffee]




Template Design pattern or Template Method Design pattern - Implementation [Coffee] - Class Diagram







































CoffeeTemplate.java

public abstract class CoffeeTemplate
{
/*
 *  prepareCoffee method is a template method,this method is final,so
 *  subclasses cannot override.
 */
public final void prepareCoffee()
{
boilWater();
addMilk();
addSugar();
addCoffeePowder();
System.out.println("Hot coffee ready.....");
}

public abstract void boilWater();

public abstract void addMilk();

public abstract void addSugar();

public abstract void addCoffeePowder();
}

BruCoffee.java

public class BruCoffee extends CoffeeTemplate
{

@Override
public void boilWater()
{
System.out.println("100 ml water boiled");

}

@Override
public void addMilk()
{
System.out.println("100 ml milk Added");

}

@Override
public void addSugar()
{
System.out.println("100 grams sugar Added");

}

@Override
public void addCoffeePowder()
{
System.out.println("10 grams Bru coffee powder Added");

}

}

NescafeCoffee.java

public class NescafeCoffee extends CoffeeTemplate
{

@Override
public void boilWater()
{
System.out.println("200 ml water boiled");

}

@Override
public void addMilk()
{
System.out.println("200 ml milk Added");

}

@Override
public void addSugar()
{
System.out.println("200 grams sugar Added");

}

@Override
public void addCoffeePowder()
{
System.out.println("20 grams Nescafe coffee powder Added");

}

}

CoffeeClient.java

public class CoffeeClient
{

public static void main( String[] args )
{

System.out.println("Bru coffee preparation\n");
CoffeeTemplate bruCoffee = new BruCoffee();
bruCoffee.prepareCoffee();

System.out.println("*******************************************");

System.out.println("Nescafe coffee preparation\n");
CoffeeTemplate NescafeCoffee = new NescafeCoffee();
NescafeCoffee.prepareCoffee();

}

}

Output

Bru coffee preparation

100 ml water boiled
100 ml milk Added
100 grams sugar Added
10 grams Bru coffee powder Added
Hot coffee ready.....
*******************************************
Nescafe coffee preparation

200 ml water boiled
200 ml milk Added
200 grams sugar Added
20 grams Nescafe coffee powder Added
Hot coffee ready.....


See also:

  • Template Design pattern or Template Method Design pattern - Introduction
  • Template Design pattern or Template Method Design pattern - Real Time Example [Coffee]
  • Template Design pattern or Template Method Design pattern - Real Time Example [Car]
  • Template Design pattern or Template Method Design pattern - Class Diagram
  • Template Design pattern or Template Method Design pattern - Implementation [Building a House]
  • Template Design pattern or Template Method Design pattern - KeyPoints
  • All Design Patterns Links
  • Saturday, 7 December 2013

    Template Design pattern or Template Method Design pattern - Implementation [Building a House]

    Master Java Design Patterns Easily!

    Subscribe to Ram N Java for step-by-step programming guides, architecture blueprints, and real-world code examples!

    🔔 Subscribe to Ram N Java

    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:

    1. Build the foundation
    2. Build the pillars
    3. Build the walls
    4. 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.

    Related Tutorials from Ram N Java


    Click here to watch in Youtube : https://www.youtube.com/watch?v=209srnMmADU

    Click the below Image to Enlarge
    Template Design pattern or Template Method Design pattern - Implementation [Building a House]

    Template Design pattern or Template Method Design pattern - Implementation [Building a House] - Class Diagram
















    HouseTemplate.java

    public abstract class HouseTemplate
    {

    // Template method is final so subclasses can't override
    public final void buildHouse()
    {
    buildFoundation();
    buildPillars();
    buildWalls();
    buildWindows();
    System.out.println("House is built.");
    }

    // Methods to be implemented by subclasses

    public abstract void buildFoundation();

    public abstract void buildPillars();

    public abstract void buildWalls();

    public abstract void buildWindows();

    }

    GlassHouse.java

    public class GlassHouse extends HouseTemplate
    {

    @Override
    public void buildFoundation()
    {
    System.out.println("Building foundation with cement,iron rods and sand");
    }

    @Override
    public void buildPillars()
    {
    System.out.println("Building Pillars with glass coating");
    }

    @Override
    public void buildWalls()
    {
    System.out.println("Building Glass Walls");
    }

    @Override
    public void buildWindows()
    {
    System.out.println("Building Glass Windows");

    }

    }

    WoodenHouse.java

    public class WoodenHouse extends HouseTemplate
    {

    @Override
    public void buildFoundation()
    {
    System.out.println("Building foundation with cement,iron rods,sand and wood");
    }

    @Override
    public void buildPillars()
    {
    System.out.println("Building Pillars with Wood coating");
    }

    @Override
    public void buildWalls()
    {
    System.out.println("Building Wooden Walls");
    }

    @Override
    public void buildWindows()
    {
    System.out.println("Building Wooden Windows");

    }

    }

    HousingClient.java

    public class HousingClient
    {

    public static void main( String[] args )
    {

    System.out.println("Build a WoodenHouse\n");
    HouseTemplate houseType = new WoodenHouse();

    // using template method
    houseType.buildHouse();
    System.out.println("************************************************************");

    System.out.println("Build a GlassHouse\n");
    houseType = new GlassHouse();

    houseType.buildHouse();
    }

    }

    Output

    Build a WoodenHouse

    Building foundation with cement,iron rods,sand and wood
    Building Pillars with Wood coating
    Building Wooden Walls
    Building Wooden Windows
    House is built.
    ************************************************************
    Build a GlassHouse

    Building foundation with cement,iron rods and sand
    Building Pillars with glass coating
    Building Glass Walls
    Building Glass Windows
    House is built.


    See also:



  • Template Design pattern or Template Method Design pattern - Introduction
  • Template Design pattern or Template Method Design pattern - Real Time Example [Coffee]
  • Template Design pattern or Template Method Design pattern - Real Time Example [Car]
  • Template Design pattern or Template Method Design pattern - Class Diagram
  • Template Design pattern or Template Method Design pattern - Implementation [Coffee]
  • Template Design pattern or Template Method Design pattern - KeyPoints
  • All Design Patterns Links
  • Template Design pattern or Template Method Design pattern - Keypoints

    Level Up Your Software Design Skills!

    Subscribe to Ram N Java for intuitive breakdowns of Gang of Four (GoF) design patterns and clean architecture principles!

    🔔 Subscribe to Ram N Java

    Overview of the Template Method Pattern

    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.

    Related Tutorials from Ram N Java


    Click here to watch in Youtube : https://www.youtube.com/watch?v=_7-6aP7Ts1w

    Click the below Image to Enlarge




    See also:

  • Template Design pattern or Template Method Design pattern - Introduction
  • Template Design pattern or Template Method Design pattern - Real Time Example [Coffee]
  • Template Design pattern or Template Method Design pattern - Real Time Example [Car]
  • Template Design pattern or Template Method Design pattern - Class Diagram
  • Template Design pattern or Template Method Design pattern - Implementation [Building a House]
  • Template Design pattern or Template Method Design pattern - Implementation [Coffee]
  • All Design Patterns Links
  • Template Design pattern or Template Method Design pattern - Real Time Example [Car]

    Master Object-Oriented Design in Java!

    Subscribe to Ram N Java for clean code practices, real-world design pattern implementations, and software design insights!

    🔔 Subscribe to Ram N Java

    The Analogy: Car Manufacturing Workflow

    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:

    1. Assemble the chassis and skeleton frame
    2. Mount the engine and transmission
    3. Install the wheels and axles
    4. 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.

    Related Tutorials from Ram N Java


    Click here to watch in Youtube : https://www.youtube.com/watch?v=oXvpL7c4k_Y

    Click the below Image to Enlarge
    Template Design pattern or Template Method Design pattern - Real Time Example [Car]

















    See also:

  • Template Design pattern or Template Method Design pattern - Introduction
  • Template Design pattern or Template Method Design pattern - Real Time Example [Coffee]
  • Template Design pattern or Template Method Design pattern - Class Diagram
  • Template Design pattern or Template Method Design pattern - Implementation [Building a House]
  • Template Design pattern or Template Method Design pattern - Implementation [Coffee]
  • Template Design pattern or Template Method Design pattern - KeyPoints
  • All Design Patterns Links
  • Template Design pattern or Template Method Design pattern - Real Time Example [Coffee]

    Master Practical Software Design Patterns!

    Subscribe to Ram N Java for clean code concepts, clear architecture diagrams, and real-world Java walkthroughs!

    🔔 Subscribe to Ram N Java

    The Concept: Real-Time Coffee Making Analogy

    When making any type of coffee—whether you prefer Bru Coffee, Nescafé, or a custom filter blend—the overarching routine follows a predefined set of actions:

    1. Boil water
    2. Add milk
    3. Add sugar
    4. Add the designated coffee powder

    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.

    Related Tutorials from Ram N Java


    Click here to watch in Youtube : https://www.youtube.com/watch?v=0AFpMUMlQkY

    Click the below Image to Enlarge
    Template Design pattern or Template Method Design pattern - Real Time Example [Coffee]


















    See also:

  • Template Design pattern or Template Method Design pattern - Introduction
  • Template Design pattern or Template Method Design pattern - Real Time Example [Car]
  • Template Design pattern or Template Method Design pattern - Class Diagram
  • Template Design pattern or Template Method Design pattern - Implementation [Building a House]
  • Template Design pattern or Template Method Design pattern - Implementation [Coffee]
  • Template Design pattern or Template Method Design pattern - KeyPoints
  • All Design Patterns Links
  • Template Design pattern or Template Method Design pattern - Class diagram

    Master Software Architecture & UML!

    Subscribe to Ram N Java for clean class diagrams, design pattern tutorials, and real-world coding guides!

    🔔 Subscribe to Ram N Java

    Anatomy of the Template Method Class Diagram

    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.

    Related Tutorials from Ram N Java


    Click here to watch in Youtube : https://www.youtube.com/watch?v=pQCAzasCgHo

    Click the below Image to Enlarge
    Template Design pattern or Template Method Design pattern - Class diagram

















    See also:

  • Template Design pattern or Template Method Design pattern - Introduction
  • Template Design pattern or Template Method Design pattern - Real Time Example [Coffee]
  • Template Design pattern or Template Method Design pattern - Real Time Example [Car]
  • Template Design pattern or Template Method Design pattern - Implementation [Building a House]
  • Template Design pattern or Template Method Design pattern - Implementation [Coffee]
  • Template Design pattern or Template Method Design pattern - KeyPoints
  • All Design Patterns Links
  • Template Design pattern or Template Method Design pattern - Introduction

    Master Object-Oriented Software Design!

    Subscribe to Ram N Java for beginner-friendly breakdowns of GoF design patterns, clean coding principles, and architecture walkthroughs!

    🔔 Subscribe to Ram N Java

    What is the Template Method Design Pattern?

    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.

    Related Tutorials from Ram N Java


    Click here to watch in Youtube : https://www.youtube.com/watch?v=bPVDEkl1z0o

    Click the below Image to Enlarge
    Template Design pattern or Template Method Design pattern - Introduction

















    See also:

  • Template Design pattern or Template Method Design pattern - Real Time Example [Coffee]
  • Template Design pattern or Template Method Design pattern - Real Time Example [Car]
  • Template Design pattern or Template Method Design pattern - Class Diagram
  • Template Design pattern or Template Method Design pattern - Implementation [Building a House]
  • Template Design pattern or Template Method Design pattern - Implementation [Coffee]
  • Template Design pattern or Template Method Design pattern - KeyPoints
  • All Design Patterns Links
  • Tutorials