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”
Explanation
In a base class (abstract), you define a finaltemplateMethod() 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
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).\