Bird
0
0
LLDsystem_design~15 mins

Template Method pattern in LLD - Deep Dive

Choose your learning style9 modes available
Overview - Template Method pattern
What is it?
The Template Method pattern is a way to define the steps of an algorithm in a fixed order, but lets some steps be changed by subclasses. It provides a skeleton of the process, while allowing parts to be customized. This helps reuse common code and keep variations organized.
Why it matters
Without the Template Method pattern, developers often copy and paste similar code with small changes, causing bugs and hard-to-maintain code. This pattern solves that by separating the stable parts from the changing parts, making software easier to extend and less error-prone.
Where it fits
Before learning this, you should understand basic object-oriented programming concepts like classes, inheritance, and polymorphism. After this, you can explore other design patterns like Strategy or Factory Method that also help with flexible code design.
Mental Model
Core Idea
A fixed process defines the overall steps, but some steps are left open for subclasses to fill in their own details.
Think of it like...
It's like a cooking recipe where the main steps are set, but you can choose different spices or toppings to make your own flavor.
┌─────────────────────────────┐
│ Template Method (Algorithm) │
├─────────────┬───────────────┤
│ Step 1      │ Fixed         │
│ Step 2      │ Abstract (hook)│
│ Step 3      │ Fixed         │
│ Step 4      │ Abstract (hook)│
│ Step 5      │ Fixed         │
└─────────────┴───────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding fixed algorithm structure
🤔
Concept: Learn that some processes have a fixed order of steps that should not change.
Imagine you have a morning routine: wake up, brush teeth, eat breakfast, leave house. This order is important and should stay the same every day.
Result
You see that some steps are stable and must happen in order.
Understanding that some processes have a fixed structure helps you see why controlling the order of steps is important.
2
FoundationRecognizing variation points in processes
🤔
Concept: Identify which steps in a process might need to change depending on the situation.
In the morning routine, maybe the breakfast changes daily: cereal one day, toast another. The rest stays the same.
Result
You realize some steps can be flexible while others remain fixed.
Knowing which parts can vary helps you design systems that are both stable and adaptable.
3
IntermediateDefining the template method in code
🤔Before reading on: do you think the template method should be implemented in subclasses or the base class? Commit to your answer.
Concept: The template method is implemented in the base class and calls other methods that subclasses override.
The base class has a method that calls several steps in order. Some steps are implemented in the base class (fixed), others are abstract and must be provided by subclasses (variable).
Result
You get a clear structure where the overall process is controlled by the base class, but details come from subclasses.
Understanding that the base class controls the flow prevents subclasses from changing the order and keeps the algorithm consistent.
4
IntermediateUsing hooks for optional customization
🤔Before reading on: do you think hooks must be overridden by subclasses or can they be optional? Commit to your answer.
Concept: Hooks are optional methods with default empty or simple behavior that subclasses can override to customize without changing the algorithm.
Hooks allow subclasses to add behavior at certain points without forcing them to implement every step. For example, a hook might be called before or after a fixed step.
Result
You can customize behavior flexibly without breaking the template method.
Knowing about hooks helps you design more flexible and less rigid templates.
5
IntermediateAvoiding code duplication with template method
🤔
Concept: The pattern helps avoid repeating the same code in multiple subclasses by putting common steps in the base class.
Instead of copying the whole algorithm in each subclass, you write it once in the base class and only override the parts that differ.
Result
Code is cleaner, easier to maintain, and less error-prone.
Recognizing how the pattern reduces duplication encourages better software design.
6
AdvancedExtending template method with multiple subclasses
🤔Before reading on: do you think multiple subclasses can share the same template method without conflicts? Commit to your answer.
Concept: Multiple subclasses can implement different variations of the steps while sharing the same overall algorithm from the base class.
Each subclass provides its own implementation of the abstract steps, allowing different behaviors under the same process structure.
Result
You get flexible and reusable code that supports many variations easily.
Understanding this shows how the pattern supports scalability and maintainability in large systems.
7
ExpertRecognizing pitfalls and misuse of template method
🤔Before reading on: do you think template method is suitable for all kinds of algorithm variations? Commit to your answer.
Concept: The pattern is best when the algorithm structure is stable; if the order or steps change often, other patterns like Strategy may be better.
Using template method when the process steps vary widely can lead to complex and fragile code. Also, deep inheritance hierarchies can make understanding flow hard.
Result
You learn when to avoid the pattern and choose alternatives.
Knowing the limits of the pattern prevents overuse and design problems in real projects.
Under the Hood
The template method is a method in a base class that calls other methods in a fixed sequence. Some of these methods are implemented in the base class (fixed steps), while others are abstract or have default implementations (hooks) that subclasses override. At runtime, the subclass's versions of these methods are called, allowing customization without changing the overall flow.
Why designed this way?
It was designed to promote code reuse and enforce a consistent algorithm structure while allowing flexibility. Before this pattern, developers often duplicated code or mixed fixed and variable parts, causing maintenance issues. The pattern balances stability and extensibility by using inheritance and polymorphism.
┌───────────────────────────────┐
│          Base Class           │
│ ┌───────────────────────────┐ │
│ │ Template Method()          │ │
│ │ ┌───────────────────────┐ │ │
│ │ │ Step1() - fixed       │ │ │
│ │ │ Step2() - abstract    │◄┼─┤
│ │ │ Step3() - fixed       │ │ │
│ │ │ Hook() - optional     │◄┼─┤
│ │ └───────────────────────┘ │ │
│ └───────────────────────────┘ │
└─────────────▲─────────────────┘
              │
       ┌──────┴───────┐
       │              │
┌─────────────┐ ┌─────────────┐
│ Subclass A  │ │ Subclass B  │
│ Overrides   │ │ Overrides   │
│ Step2() and │ │ Step2() and │
│ Hook()      │ │ Hook()      │
└─────────────┘ └─────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does the template method pattern allow subclasses to change the order of steps? Commit yes or no.
Common Belief:Subclasses can change the order of steps in the algorithm by overriding the template method.
Tap to reveal reality
Reality:The template method itself is defined in the base class and controls the order; subclasses only override specific steps, not the sequence.
Why it matters:If subclasses change the order, it breaks the algorithm's integrity and can cause bugs or inconsistent behavior.
Quick: Do you think template method is the best choice when the algorithm steps change frequently? Commit yes or no.
Common Belief:Template method is always the best pattern for any algorithm variation.
Tap to reveal reality
Reality:Template method works best when the overall algorithm structure is stable; if steps or order change often, other patterns like Strategy are better.
Why it matters:Using template method in unstable algorithms leads to complex inheritance and fragile code.
Quick: Can template method be used without inheritance? Commit yes or no.
Common Belief:Template method can be implemented without using inheritance.
Tap to reveal reality
Reality:Template method relies on inheritance and polymorphism to allow subclasses to override steps.
Why it matters:Trying to use it without inheritance misses the core mechanism and leads to poor design.
Quick: Do hooks have to be overridden by subclasses? Commit yes or no.
Common Belief:Hooks must always be implemented by subclasses.
Tap to reveal reality
Reality:Hooks have default implementations and are optional to override.
Why it matters:Misunderstanding hooks can cause unnecessary code and reduce flexibility.
Expert Zone
1
Hooks can be used to provide extension points without forcing subclasses to implement them, reducing boilerplate code.
2
Template method can be combined with other patterns like Factory Method to create complex but flexible algorithms.
3
Deep inheritance hierarchies with many template methods can make debugging difficult because the flow is split across classes.
When NOT to use
Avoid template method when the algorithm steps or their order change frequently or need to be selected at runtime. Use Strategy pattern for runtime flexibility or Composition over Inheritance to reduce tight coupling.
Production Patterns
In real systems, template method is often used in frameworks to define lifecycle methods (e.g., initializing, processing, cleaning up) where users override hooks to customize behavior without changing the framework's core flow.
Connections
Strategy pattern
Alternative pattern for algorithm variation using composition instead of inheritance
Knowing template method helps understand when to use inheritance-based control flow versus composition-based interchangeable behaviors.
Software frameworks
Template method is commonly used to define fixed workflows with customizable steps in frameworks
Recognizing this pattern explains how frameworks allow users to plug in custom code without changing core logic.
Cooking recipes
Both define a fixed sequence of steps with room for variation in ingredients or techniques
Understanding this connection helps grasp the balance between fixed structure and flexible details in processes.
Common Pitfalls
#1Trying to override the template method itself in subclasses to change the algorithm order.
Wrong approach:class Subclass(Base): def template_method(self): # Changed order self.step3() self.step1() self.step2()
Correct approach:class Subclass(Base): def step2(self): # Custom step implementation pass
Root cause:Misunderstanding that the template method controls the algorithm flow and should not be changed by subclasses.
#2Duplicating the whole algorithm in each subclass instead of using the template method.
Wrong approach:class Subclass(Base): def template_method(self): # Copy-pasted entire algorithm self.step1() # Custom code self.step2() self.step3()
Correct approach:class Subclass(Base): def step2(self): # Only override the variable part pass
Root cause:Not leveraging inheritance and polymorphism to reuse the fixed algorithm.
#3Forcing subclasses to implement all steps even when some are optional.
Wrong approach:class Base: def hook(self): raise NotImplementedError class Subclass(Base): def hook(self): # Must implement even if empty
Correct approach:class Base: def hook(self): pass # Default empty implementation class Subclass(Base): # Override only if needed
Root cause:Not using hooks with default implementations to allow optional overrides.
Key Takeaways
Template Method pattern defines a fixed algorithm structure in a base class while allowing subclasses to customize specific steps.
It promotes code reuse and consistency by separating stable parts from variable parts of an algorithm.
Hooks provide optional extension points that subclasses can override without forcing implementation.
The pattern relies on inheritance and polymorphism to control the flow and customization.
Use Template Method when the overall process is stable but some steps need flexible implementations.