Bird
0
0
LLDsystem_design~3 mins

Why Template Method pattern in LLD? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could write a recipe once and easily create many variations without rewriting everything?

The Scenario

Imagine you have to build several similar workflows by writing each step from scratch every time. For example, making different types of coffee manually by following the entire recipe each time without any shared structure.

The Problem

This manual way is slow and error-prone because you repeat common steps again and again. If you want to change a shared step, you must update every single workflow separately, which is painful and easy to forget.

The Solution

The Template Method pattern solves this by defining a fixed skeleton of an algorithm in one place. It lets you reuse the common steps and only customize the parts that differ. This way, you avoid repetition and keep your code clean and easy to maintain.

Before vs After
Before
class Coffee {
  void make() {
    boilWater();
    brewCoffee();
    pourInCup();
    addSugar();
  }
}

class Tea {
  void make() {
    boilWater();
    steepTea();
    pourInCup();
    addLemon();
  }
}
After
abstract class Beverage {
  final void prepare() {
    boilWater();
    brew();
    pourInCup();
    addCondiments();
  }
  abstract void brew();
  abstract void addCondiments();
  void boilWater() { /* boil water */ }
  void pourInCup() { /* pour into cup */ }
}

class Coffee extends Beverage {
  void brew() { /* brew coffee */ }
  void addCondiments() { /* add sugar */ }
}

class Tea extends Beverage {
  void brew() { /* steep tea */ }
  void addCondiments() { /* add lemon */ }
}
What It Enables

It enables building flexible, reusable workflows where common steps are fixed and only the unique parts vary, making maintenance and updates simple.

Real Life Example

Think of a coffee shop where the barista follows a standard process for all drinks but customizes brewing and toppings depending on the order, ensuring consistency and efficiency.

Key Takeaways

Defines a fixed algorithm structure with customizable steps.

Reduces code duplication and eases maintenance.

Separates common workflow from specific details.