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 Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Java
  4. Revisiting the Template Method Design Pattern in Java

Revisiting the Template Method Design Pattern in Java

Want to learn more about the template method design pattern in Java. Check out this post where we explore classic GoF template method implementation.

Grzegorz Piwowarek user avatar by
Grzegorz Piwowarek
·
Nov. 12, 18 · Tutorial
Like (9)
Save
Tweet
Share
12.63K Views

Join the DZone community and get the full member experience.

Join For Free

The conciseness of Java 8 lambda expressions sheds a new light on classic GoF design patterns. By leveraging functional programming, we can get the same benefits with much less coupling and ceremony – the Template method is a great example of that.

Classic GoF Template Method Implementation

The template method design pattern is one of 23 design patterns described by the Gang of Four – utilizing it makes it easy to conform to the Open-Closed and Hollywood principles.

Simply put, it facilitates defining a skeleton (algorithm invariants) of a certain algorithm where users can fill-in-the-blanks, which is achieved by overriding abstract methods exposed by an abstract class defining the skeleton implementation.

Getting more practical, imagine scenarios like logging execution time of some action, running your code within a transaction, or a classical JUnit workflow where we’re responsible for filling in the blanks in form of before/after/test methods — those are scenarios where the pattern shines.

Let’s have a look at a fairly simple example that surrounds our code with naive execution time logging.

Classically-trained GoF design pattern practitioners would implement the idea using abstract classes:

package com.pivovarit.template_method.gof;

import java.time.Duration;
import java.time.LocalTime;

abstract class AbstractTimeLoggingMethod {

    abstract void run();

    public void runWithTimeLogging() {
        var before = LocalTime.now();
        run();
        var after = LocalTime.now();
        System.out.printf(
          "Execution took: %d ms%n", 
          Duration.between(before, after).toMillis());
    }
}


And then, if we want to wrap our piece of code with the logging logic, we just need to extend the class and then use the public method:

public static void main(String[] args) {
    var fetchAndLog = new AbstractTimeLoggingMethod() {
        @Override
        void run() {
            findById(42);
        }
    };

    fetchAndLog.runWithTimeLogging(); // Execution took: 1005 ms
}


However, since it relies on inheritance, this approach is quite invasive – it tightly couples classes together and screams with excessive boilerplate (not even mentioning the fact that each subclass becomes a new *.class file eventually).

Simplifying Template Method With Functions

Having new tools in our toolbox, we can achieve a similar effect using a lightweight version of the above without using inheritance by utilizing functional programming ideas. Since we can now pass functions around, why not do the same here?

So, instead of defining a skeleton by using an abstract class, we can do that in a single method that accepts a functional interface:

final class TemplateMethodUtil {

    private TemplateMethodUtil() {
    }

    static void runWithExecutionTimeLogging(Runnable action) {
        var before = LocalTime.now();
        action.run();
        var after = LocalTime.now();
        System.out.printf(
          "Execution took: %d ms%n", 
          Duration.between(before, after).toMillis());
    }
}


And now, whenever we want to opt-in, it’s enough to just call the util method to leverage the compile-time aspect’ish semantics:

TemplateMethodUtil.runWithExecutionTimeLogging(() -> findById(42));


Want to orchestrate multiple calls? Not a problem:

static void orchestrate(Runnable step1, Runnable step2) {
    System.out.println("starting...");
    step1.run();
    step2.run();
    System.out.println("ending...");
}


And in action:

TemplateMethodUtil.orchestrate(
  () -> System.out.println("a"),
  () -> System.out.println("b"));

starting...
a
b
ending...


Summary

The GoF book is full of canonical ideas, but it’s still worth revisiting them as new ways emerge that enable better implementations.

Code snippets can be found on GitHub.

Template Design Java (programming language)

Published at DZone with permission of Grzegorz Piwowarek, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • How to Submit a Post to DZone
  • API Design Patterns Review
  • What Is a Kubernetes CI/CD Pipeline?
  • Bye Bye, Regular Dev [Comic]

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: