Skip to main content

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”
template method

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

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).\