DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Exploring Exciting New Features in Java 17 With Examples
  • Template-Based PDF Document Generation in Java
  • Template Design Pattern or Template Method Design Pattern in Java
  • Spring Beans With Auto-Generated Implementations: How-To

Trending

  • Evolving Spring Boot APIs to an Event-Driven Mesh
  • Beyond Conversation: Mastering Context with Claude Code Skills and Agents
  • How to Format Articles for DZone
  • Stop Debugging Glue Jobs Manually: Building an Agentic Observability Layer for Data Pipelines
  1. DZone
  2. Coding
  3. Java
  4. Secret Recipe of the Template Method: Po Learns the Art of Structured Cooking

Secret Recipe of the Template Method: Po Learns the Art of Structured Cooking

Po learns how fixed structure with flexible ingredients makes the perfect noodle soup and Java code through the Template Method pattern in both OOP and functional styles.

By 
Shaamik Mitraa user avatar
Shaamik Mitraa
·
Jul. 11, 25 · Tutorial
Likes (0)
Comment
Save
Tweet
Share
2.0K Views

Join the DZone community and get the full member experience.

Join For Free

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)

Java
 
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."

Java
 
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

Java
 
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 and 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

Java
 
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!"

Also read...

  • Part 1 – Kung Fu Code: Master Shifu Teaches Strategy Pattern to Po – The Functional Way
  • Part 2 – Code of Shadows: Master Shifu and Po Use Functional Java to Solve the Decorator Pattern Mystery
  • Part 3 – Kung Fu Commands: Shifu Teaches Po the Command Pattern with Java Functional Interfaces
Java (programming language) Template User-defined function

Published at DZone with permission of Shaamik Mitraa. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Exploring Exciting New Features in Java 17 With Examples
  • Template-Based PDF Document Generation in Java
  • Template Design Pattern or Template Method Design Pattern in Java
  • Spring Beans With Auto-Generated Implementations: How-To

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook