Gala at the Jade Palace
A grand gala was being held at the Jade Palace. The Furious Five were preparing, and Po was helping his father, Mr. Ping, in the kitchen. But as always, Po had questions.
Po (curious): "Dad, how do you always make the perfect noodle soup no matter what the ingredients are?"
Mr. Ping (smiling wisely): "Ah, my boy, that’s because I follow the secret recipe—a fixed template!"
Mr. Ping Reveals the Template Method Pattern
Mr. Ping: "Po, the Template Method Pattern is like my noodle recipe. The skeleton of the cooking steps stays the same, but the ingredients and spices can vary!"
Po: "Wait, you mean like... every dish has a beginning, middle, and end—but I can change what goes inside?"
Mr. Ping: "Exactly! The fixed steps are defined in a base class, but subclasses—or in our case, specific dishes—override the variable parts."
Traditional Template Method in Java (Classic OOP)
public abstract class DishRecipe {
// Template method
public final void cookDish() {
boilWater();
addIngredients();
addSpices();
serve();
}
private void boilWater() {
System.out.println("Boiling water...");
}
protected abstract void addIngredients();
protected abstract void addSpices();
private void serve() {
System.out.println("Serving hot!");
}
}
class NoodleSoup extends DishRecipe {
protected void addIngredients() {
System.out.println("Adding noodles, veggies, and tofu.");
}
protected void addSpices() {
System.out.println("Adding soy sauce and pepper.");
}
}
class DumplingSoup extends DishRecipe {
protected void addIngredients() {
System.out.println("Adding dumplings and bok choy.");
}
protected void addSpices() {
System.out.println("Adding garlic and sesame oil.");
}
}
public class TraditionalCookingMain {
public static void main(String[] args) {
DishRecipe noodle = new NoodleSoup();
noodle.cookDish();
System.out.println("\n---\n");
DishRecipe dumpling = new DumplingSoup();
dumpling.cookDish();
}
}
//Output
Boiling water...
Adding noodles, veggies, and tofu.
Adding soy sauce and pepper.
Serving hot!
---
Boiling water...
Adding dumplings and bok choy.
Adding garlic and sesame oil.
Serving hot!
Po: "Whoa! So each dish keeps the boiling and serving, but mixes up the center part. Just like kung fu forms!"
Functional Template Method Style
Po: "Dad, can I make it more... functional?"
Mr. Ping: "Yes, my son. We now wield the power of higher-order functions."
import java.util.function.Consumer;
public class FunctionalTemplate {
public static <T> void prepareDish(T dishName, Runnable boil, Consumer<T> addIngredients, Consumer<T> addSpices, Runnable serve) {
boil.run();
addIngredients.accept(dishName);
addSpices.accept(dishName);
serve.run();
}
public static void main(String[] args) {
prepareDish("Noodle Soup",
() -> System.out.println("Boiling water..."),
dish -> System.out.println("Adding noodles, veggies, and tofu to " + dish),
dish -> System.out.println("Adding soy sauce and pepper to " + dish),
() -> System.out.println("Serving hot!")
);
prepareDish("Dumpling Soup",
() -> System.out.println("Boiling water..."),
dish -> System.out.println("Adding dumplings and bok choy to " + dish),
dish -> System.out.println("Adding garlic and sesame oil to " + dish),
() -> System.out.println("Serving hot!")
);
}
}
Po: "Look dad! Now we can cook anything, as long as we plug in the steps! It's like building recipes with Lego blocks!"
Mr. Ping (beaming): "Ah, my son. You are now a chef who understands both structure and flavor."
Real-World Use Case – Coffee Brewing Machines
Po: “Dad, Now I want to build the perfect coffee-making machine, just like our noodle soup recipe!”
Mr. Ping: “Ah, coffee, the elixir of monks and night-coders! Use the same template method wisdom, my son.”
Step-by-Step Template – Java OOP Coffee Brewer
abstract class CoffeeMachine {
// Template Method
public final void brewCoffee() {
boilWater();
addCoffeeBeans();
brew();
pourInCup();
}
private void boilWater() {
System.out.println("Boiling water...");
}
protected abstract void addCoffeeBeans();
protected abstract void brew();
private void pourInCup() {
System.out.println("Pouring into cup.");
}
}
class EspressoMachine extends CoffeeMachine {
protected void addCoffeeBeans() {
System.out.println("Adding finely ground espresso beans.");
}
protected void brew() {
System.out.println("Brewing espresso under high pressure.");
}
}
class DripCoffeeMachine extends CoffeeMachine {
protected void addCoffeeBeans() {
System.out.println("Adding medium ground coffee.");
}
protected void brew() {
System.out.println("Dripping hot water through the grounds.");
}
}
public class CoffeeMain {
public static void main(String[] args) {
CoffeeMachine espresso = new EspressoMachine();
espresso.brewCoffee();
System.out.println("\n---\n");
CoffeeMachine drip = new DripCoffeeMachine();
drip.brewCoffee();
}
}
//Ouput
Boiling water...
Adding finely ground espresso beans.
Brewing espresso under high pressure.
Pouring into cup.
---
Boiling water...
Adding medium ground coffee.
Dripping hot water through the grounds.
Pouring into cup.
Functional & Generic Coffee Brewing (Higher-Order Zen)
Po, feeling enlightened, says:
Po: “Dad! What if I want to make Green Tea or Hot Chocolate too?”
Mr. Ping (smirking): “Ahhh... Time to use the Generic Template of Harmony™!”
Functional Java Template for Any Beverage
import java.util.function.Consumer;
public class BeverageBrewer {
public static <T> void brew(T name, Runnable boil, Consumer<T> addIngredients, Consumer<T> brewMethod, Runnable pour) {
boil.run();
addIngredients.accept(name);
brewMethod.accept(name);
pour.run();
}
public static void main(String[] args) {
brew("Espresso",
() -> System.out.println("Boiling water..."),
drink -> System.out.println("Adding espresso grounds to " + drink),
drink -> System.out.println("Brewing under pressure for " + drink),
() -> System.out.println("Pouring into espresso cup.")
);
System.out.println("\n---\n");
brew("Green Tea",
() -> System.out.println("Boiling water..."),
drink -> System.out.println("Adding green tea leaves to " + drink),
drink -> System.out.println("Steeping " + drink + " gently."),
() -> System.out.println("Pouring into tea cup.")
);
}
}
//Output
Boiling water...
Adding espresso grounds to Espresso
Brewing under pressure for Espresso
Pouring into espresso cup.
---
Boiling water...
Adding green tea leaves to Green Tea
Steeping Green Tea gently.
Pouring into tea cup.
Mr. Ping’s Brewing Wisdom
“In code as in cooking, keep your recipe fixed… but let your ingredients dance.”
Template Pattern gives you structure.
Higher-order functions give you flexibility.
Use both, and your code becomes as tasty as dumplings dipped in wisdom!
Mr. Ping: "Po, a great chef doesn't just follow steps. He defines the structure—but lets each ingredient bring its own soul."
Po: "And I shall pass down the Template protocol to my children’s children’s children!
Other Articles in this Series.
================================
1.Kung Fu Code: Master Shifu Teaches Strategy Pattern to Po – the Functional Way!
2. Code of Shadows:Mastering Decorator Pattern in Java – Po & Shifu’s Thriller Story of Clean Code
Post a Comment