1ae1de6d0d2a87e6834da409bfd891b2 Template design pattern

Template design pattern

 The Template Method design pattern is a behavioral pattern that defines the skeleton of an algorithm in a base (abstract) class but lets subclasses override specific steps without changing the algorithm's structure



In simple words:
👉 You outline the big steps in a base class.
👉 You let child classes fill in the details by overriding some of those steps.


Key Ideas:

  • The algorithm's overall flow stays the same (defined in the base class).

  • Subclasses customize specific steps.

  • It follows the "Don't call us, we'll call you" principle — the base class controls when subclass methods are called.


Real-life Example:

  • Cooking a meal (Template):

    • Prepare ingredients (can vary)

    • Cook (can vary)

    • Serve (common step)

Different meals (Pizza, Pasta) will prepare and cook differently, but the overall process stays the same.


Example (Very Simple)

Pseudo-Java/Python:


abstract class Meal { void makeMeal() { prepareIngredients(); cook(); eat(); } abstract void prepareIngredients(); abstract void cook(); void eat() { System.out.println("Mmm, delicious!"); } } class PizzaMeal extends Meal { void prepareIngredients() { System.out.println("Prepare dough, sauce, cheese."); } void cook() { System.out.println("Bake in oven."); } }

Then:


Meal dinner = new PizzaMeal(); dinner.makeMeal();

Why Use Template Pattern?

✅ Avoids code duplication (shared structure).
✅ Promotes code reuse (shared behavior in base class).
✅ Forces a standard procedure with customizable parts.


One-liner definition:

"Template Method Pattern lets you define the outline of an operation, deferring some steps to subclasses."



java implementation:

// Abstract Class abstract class Game { abstract void initialize(); abstract void startPlay(); abstract void endPlay(); // Template Method public final void play() { initialize(); startPlay(); endPlay(); } } // Concrete Class class Football extends Game { void initialize() { System.out.println("Football Game Initialized."); } void startPlay() { System.out.println("Football Game Started."); } void endPlay() { System.out.println("Football Game Finished."); } } // Usage public class Main { public static void main(String[] args) { Game game = new Football(); game.play(); } }



python implementation:


from abc import ABC, abstractmethod # Abstract Class class Game(ABC): def play(self): self.initialize() self.start_play() self.end_play() @abstractmethod def initialize(self): pass @abstractmethod def start_play(self): pass @abstractmethod def end_play(self): pass # Concrete Class class Football(Game): def initialize(self): print("Football Game Initialized.") def start_play(self): print("Football Game Started.") def end_play(self): print("Football Game Finished.") # Usage game = Football() game.play()


 

Post a Comment

0 Comments