> ## Documentation Index
> Fetch the complete documentation index at: https://akshanshgusain.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Template Method Pattern

<Note>
  [Python Code example](https://github.com/akshanshgusain/design_patterns_py/tree/master/behavioral/templateMethod)
</Note>

## Definition

**“Template Method is a behavioral design pattern that allows you to define a skeleton of an algorithm in a base class
and let subclasses override steps without changing the overall algorithm’s structure”**

<Frame>
  <img src="https://mintcdn.com/akshanshgusain/71uOfn3470lYB6q1/lld/fundamentals/patterns/Behavioral/images/template_method_uml.png?fit=max&auto=format&n=71uOfn3470lYB6q1&q=85&s=31c58246c1359dc8ab4b1fbdead647fc" alt="template method" width="1352" height="828" data-path="lld/fundamentals/patterns/Behavioral/images/template_method_uml.png" />
</Frame>

## Explanation

In a base class (abstract), you define a final `templateMethod()` that calls several primitive operations (some abstract,
some with default implementation). Subclasses override these primitive methods to provide behavior for specific steps.
The template method enforces the algorithm’s order. The client calls `templateMethod()`, and the subclass-specific details
execute within.

## Code

```python theme={null}
class Game:
    def play(self):
        self.initialize()
        self.startPlay()
        self.endPlay()
    def initialize(self): pass
    def startPlay(self): pass
    def endPlay(self): pass

class Football(Game):
    def initialize(self): print("Football Game Initialized")
    def startPlay(self): print("Football Game Started")
    def endPlay(self): print("Football Game Finished")

# Usage:
game = Football()
game.play()  # calls template (initialize/start/end in sequence)

```

## Analogy

A cooking recipe (template) with some flexible steps. For example, a recipe for making a sandwich: base steps are (1) lay
bread, (2) add filling, (3) close bread. The exact filling is determined by a subclass (e.g. ham sandwich or veggie
sandwich). The sequence (algorithm) is fixed by the recipe (template method), but the details vary.

## Interview Insights

**Common uses**: When multiple classes share a common algorithm structure but differ in specific steps. e.g. different
games (Cricket, Football) in game simulations, data export templates, UI rendering pipelines. Useful when you want to
avoid duplication of common steps.\
**Advantages**: Encapsulates common behavior in base class. Enforces an invariant overall process. Subclasses only need
to implement variable parts. Increases code reuse.\
**Disadvantages**: Less flexible than Strategy: algorithm structure is fixed at compile time. Overuse can lead to too many abstract methods. Requires inheritance (can't change algorithm at runtime easily).\\
