The Template Method Pattern is a behavioral design pattern that defines the skeleton of an algorithm in an abstract base class, allowing subclasses to redefine certain steps without altering the overall structure.
In our example, we define an abstract class called CoffeeTemplate containing:
Abstract Methods:boilWater(), addMilk(), addSugar(), and addCoffeePowder(). Subclasses implement these specific steps.
Template Method:prepareCoffee(). This method executes the sequence of steps and is marked final so subclasses cannot alter the overall algorithm.
Java Implementation Breakdown
Here is how the core structure is laid out in code:
// Abstract Template Class
public abstract class CoffeeTemplate {
// Template method defined as final
public final void prepareCoffee() {
boilWater();
addMilk();
addSugar();
addCoffeePowder();
System.out.println("Coffee is ready!\n");
}
public abstract void boilWater();
public abstract void addMilk();
public abstract void addSugar();
public abstract void addCoffeePowder();
}
The concrete classes BruCoffee and NescafeCoffee extend CoffeeTemplate and specify the exact quantities and powder types. The client simply invokes prepareCoffee(), maintaining clean separation of concerns and eliminating code duplication.
This post was really helpful. Also love the way you explain. Thank you.
ReplyDeleteReport template design