TechnologyZer
technologyzer.com

Mastering the Template Design Pattern: Consistent Algorithms with Customizable Steps

Brewing Coffee

Introduction to Template Design Pattern

Template Design Pattern is a behavioral design pattern that outlines the structure of an algorithm in a base class while allowing subclasses to override specific implementation details without altering the overall sequence. This ensures that the main steps of the algorithm remain consistent across different implementations.

Components of the Template Method Design Pattern

  1. Abstract Class:
    • Defines the template method that contains the skeleton of the algorithm.
    • Implements some of the steps (methods) of the algorithm, either concretely or as abstract methods that must be implemented by subclasses.
    • Ensures that the overall structure of the algorithm is maintained and allows subclasses to override specific steps.
  2. Template Method:
    • A method defined in the abstract class that contains the algorithm’s structure.
    • This method calls other methods (some of which may be abstract) to perform the steps of the algorithm.
    • It is usually declared final to prevent subclasses from altering the algorithm’s structure.
  3. Concrete Class:
    • Subclasses of the abstract class.
    • Implement the abstract methods defined in the abstract class.
    • Can override some of the methods in the abstract class to provide specific implementations for certain steps of the algorithm.

Sample Code for Template Design Pattern

public abstract class Beverage {
    abstract void brew();
    abstract void addCondiments();
    private void boilWater(){
        System.out.println("Boiling Water..!!");
    }
    private void pourInCup(){
        System.out.println("Pouring into Cup..!!");
    }

    public final void prepareBeverage(){
        boilWater();
        brew();
        pourInCup();
        addCondiments();
    }
}

public class Tea extends Beverage{
    @Override
    void brew() {
        System.out.println("Steeping the Tea..!!");
    }

    @Override
    void addCondiments() {
        System.out.println("Adding Lemon..!!");
    }
}

public class Coffee extends Beverage{
    @Override
    void brew() {
        System.out.println("Dripping Coffee through filter..!!");
    }

    @Override
    void addCondiments() {
        System.out.println("Adding sugar and milk..!!");
    }
}

public class Main {
    public static void main(String[] args) {
        Beverage tea = new Tea();
        System.out.println("Preparing Tea..!!");
        tea.prepareBeverage();

        Beverage coffee = new Coffee();
        System.out.println("Preparing Coffee..!!");
        coffee.prepareBeverage();
    }
}

Leave a Comment