Design Patterns
Template Method

Template Method

Template Method Pattern: The Superhero Training Protocol

Imagine S.H.I.E.L.D. has a standard training protocol for all rookie agents—warm-up, strength training, combat skills, and cool down. While the overall structure remains the same, the specific exercises vary based on the agent's abilities. Captain America might do 500 push-ups for strength training, while Black Widow focuses on advanced martial arts. This standardized approach with customizable steps is what the Template Method pattern is all about!

The Template Method pattern defines the skeleton of an algorithm in the superclass but lets subclasses override specific steps of the algorithm without changing its structure. It turns algorithm steps into methods and calls them in a specific sequence from a single "template method."

The Problem: Algorithm Skeleton with Variations

Consider building different types of houses—a wooden house, a brick house, and a concrete house. The construction process follows a similar sequence for all three:

  1. Lay the foundation
  2. Build the walls
  3. Install the roof
  4. Set up the interior

While the sequence remains the same, the implementation of each step varies depending on the house type. Without the Template Method pattern, we might end up with redundant code and a lack of consistency across implementations.

Enter the Template Method Pattern

The Template Method pattern provides a template (the algorithm skeleton) with "hooks" (methods that subclasses can override) to customize behavior:

Loading diagram...

Let's implement a simple example using the superhero training protocol:

House Building Example

Let's implement the house building scenario mentioned earlier using the Template Method pattern:

Beverage Preparation Example

A common real-world example of the Template Method pattern is beverage preparation. Let's implement a coffee and tea preparation system:

Data Processing Example

Another practical application of the Template Method pattern is in data processing pipelines. Let's implement a file processing system:

Hooks vs. Abstract Methods

In the Template Method pattern, there are two types of methods that subclasses can implement:

  1. Abstract Methods: Required methods that must be implemented by all subclasses. These typically represent essential steps in the algorithm that will always vary.

  2. Hooks: Optional methods with default implementations that subclasses can choose to override. These allow for optional customization and are especially useful for conditional steps.

The key difference:

  • Abstract methods say: "You MUST implement this step"
  • Hooks say: "You CAN customize this step if you want"

The "Hollywood Principle"

The Template Method pattern follows the "Hollywood Principle": "Don't call us, we'll call you." The superclass calls the subclass methods when it needs them, rather than the subclass calling methods on the superclass. This inversion of control helps maintain a clear hierarchy and promotes loose coupling.

Template Method vs. Strategy Pattern

Both the Template Method and Strategy patterns deal with algorithmic flexibility, but they do so in different ways:

  • Template Method: Uses inheritance to vary parts of an algorithm. The algorithm structure is fixed in the parent class, while specific steps are implemented in subclasses.

  • Strategy: Uses composition to change the entire algorithm at runtime. Different strategies can be swapped in and out, providing totally different implementations.

Think of it this way:

  • Template Method says: "Here's the recipe, add your own twist to certain steps"
  • Strategy says: "Choose any cooking style you want for this meal"

Advantages of the Template Method Pattern

  1. Code Reuse: Common algorithm structure is defined once in the parent class.
  2. Controlled Extension: Subclasses can only modify specific steps of the algorithm, maintaining overall consistency.
  3. Enforced Structure: All implementations follow the same general structure, making the code more maintainable.
  4. Separation of Concerns: The pattern naturally separates invariant parts from variant parts.
  5. Flexibility with Control: Hooks provide optional customization without sacrificing control over the algorithm's structure.

Disadvantages of the Template Method Pattern

  1. Inheritance Limitations: The pattern relies on inheritance, which can sometimes lead to rigid hierarchies.
  2. Understanding the Flow: The algorithm flow can be harder to understand since it's split between parent and child classes.
  3. Versioning Challenges: Changes to the template method might inadvertently break subclasses.
  4. Limited Runtime Flexibility: Unlike Strategy, you can't easily change the algorithm implementation at runtime.

When to Use the Template Method Pattern

The Template Method pattern is ideal when:

  1. You want to implement the invariant parts of an algorithm once and leave the variant parts to subclasses.
  2. Several classes implement algorithms with similar steps in the same order, but with different implementations of these steps.
  3. You want to control how subclasses extend your algorithm (with hooks).
  4. You need to factor out common behavior in related classes to avoid code duplication.

Remember, just like Nick Fury's standardized S.H.I.E.L.D. protocols that are adapted for each Avenger's unique abilities, the Template Method pattern provides a consistent framework with room for customization!