Template Method Design Pattern in Java

1. Definition

The Template Method Design Pattern defines the program skeleton of an algorithm in a method in an algorithm class but delays some steps to subclasses. It allows subclasses to redefine certain steps of an algorithm without changing the algorithm's structure.

2. Problem Statement

How can we ensure that the structure of an algorithm remains constant while allowing some steps of the algorithm to be changed by the client?

3. Solution

The Template Method Pattern solves this problem by breaking the algorithm into a series of steps, and then it delegates the responsibility of some steps to the subclasses, allowing them to be implemented differently.

4. Real-World Use Cases

1. Building a house with the same blueprint but different interior designs.

2. A software build process where some steps might vary depending on the platform.

3. Cooking recipes where some steps might be optional.

5. Implementation Steps

1. Create an abstract class with a template method.

2. The template method defines the structure of the algorithm.

3. Some steps of the algorithm are implemented directly in this class.

4. Other steps are abstract and must be implemented in subclasses.

6. Implementation

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

    // Default implementation of steps
    protected void initialize() {
        System.out.println("Game initialized.");
    }

    // Abstract methods to be implemented by subclasses
    protected abstract void startPlay();
    protected abstract void endPlay();
}

// Concrete Class
class Football extends Game {
    @Override
    protected void startPlay() {
        System.out.println("Football game started.");
    }

    @Override
    protected void endPlay() {
        System.out.println("Football game finished.");
    }
}

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

Output:

Game initialized.
Football game started.
Football game finished.

Explanation

The Game class provides the template method play() which ensures the structure of the game remains constant (initialize, start, end). However, the exact steps of startPlay and endPlay are left abstract, allowing subclasses like Football to provide their own implementation.

7. When to use?

Use the Template Method Pattern when:

1. The invariant parts of an algorithm should be centralized in one location to avoid duplication.

2. Common behavior among subclasses should be factored and localized in a common class to avoid errors.

3. Subclasses need to extend only particular parts of an algorithm without changing its structure.


Comments