Template Method Design Pattern

Back To Index

Overview

The Template Method Design Pattern defines the skeleton of an algorithm in a superclass while allowing subclasses to redefine certain steps without changing the algorithm's structure.

Key Characteristics

Implementation

The following is an example of a Template Method implementation in Java:


// Abstract class
abstract class Game {
    // Template method
    public final void play() {
        initialize();
        startPlay();
        endPlay();
    }

    protected abstract void initialize();
    protected abstract void startPlay();
    protected abstract void endPlay();
}

// Concrete class 1
class Football extends Game {
    @Override
    protected void initialize() {
        System.out.println("Football Game Initialized. Start playing.");
    }

    @Override
    protected void startPlay() {
        System.out.println("Football Game Started. Enjoy the game!");
    }

    @Override
    protected void endPlay() {
        System.out.println("Football Game Finished!");
    }
}

// Concrete class 2
class Cricket extends Game {
    @Override
    protected void initialize() {
        System.out.println("Cricket Game Initialized. Start playing.");
    }

    @Override
    protected void startPlay() {
        System.out.println("Cricket Game Started. Enjoy the game!");
    }

    @Override
    protected void endPlay() {
        System.out.println("Cricket Game Finished!");
    }
}

// Demo
public class TemplateMethodDemo {
    public static void main(String[] args) {
        Game game = new Football();
        game.play();

        System.out.println();

        game = new Cricket();
        game.play();
    }
}
    

When to Use

Advantages

Disadvantages

Back To Index