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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Automated Bug Fixing: From Templates to AI Agents
  • Dynamic File Upload Component in Salesforce LWC
  • Safeguarding Web Applications With Cloud Service Providers: Anti-CSRF Tokenization Best Practices
  • Make Your Backstage Templates Resilient

Trending

  • Comparing SaaS vs. PaaS for Kafka and Flink Data Streaming
  • Scaling in Practice: Caching and Rate-Limiting With Redis and Next.js
  • Event-Driven Architectures: Designing Scalable and Resilient Cloud Solutions
  • A Guide to Developing Large Language Models Part 1: Pretraining

Template Method Pattern- Using Lambda Expressions, Default Methods

By 
Mohamed Sanaulla user avatar
Mohamed Sanaulla
·
Apr. 25, 13 · Interview
Likes (0)
Comment
Save
Tweet
Share
12.7K Views

Join the DZone community and get the full member experience.

Join For Free

Template Method pattern is one of the 23 design patterns explained in the famous Design Patterns book by Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides. The intent of this pattern is stated as:

Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. TemplateMethod lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.

To explain in simple terms, consider the following scenario: Assume there is a workflow system in which 4 tasks have to be performed in the given order so as to successfully complete the workflow. Some of the tasks out of the 4 tasks can be customised by different workflow system implementation.

Template Method pattern can be applied to above scenario by encapsulating the workflow system into an abstract class with few of the tasks out of the 4 tasks implemented. And leave the implementation of remaining tasks to the subclasses of the abstract class.

So this is what you see when the above description is implemented:

/**
 * Abstract Workflow system
 */
abstract class WorkflowManager2{
  public void doTask1(){
    System.out.println("Doing Task1...");
  }
 
  public abstract void doTask2();
 
  public abstract void doTask3();
 
  public void doTask4(){
    System.out.println("Doing Task4...");
  }
}
 
/**
 * One of the extensions of the abstract workflow system
 */
class WorkflowManager2Impl1 extends WorkflowManager2{
  @Override
  public void doTask2(){
    System.out.println("Doing Task2.1...");
  }
 
  @Override
  public void doTask3(){
    System.out.println("Doing Task3.1...");
  }
}
 
/**
 * Other extension of the abstract workflow system
 */
class WorkflowManager2Impl2 extends WorkflowManager2{
  @Override
  public void doTask2(){
    System.out.println("Doing Task2.2...");
  }
 
  @Override
  public void doTask3(){
    System.out.println("Doing Task3.2...");
  }
}

Let me just go ahead and show how these workflow implementations are used:

public class TemplateMethodPattern {
  public static void main(String[] args) {
   initiateWorkFlow(new WorkflowManager2Impl1());
   initiateWorkFlow(new WorkflowManager2Impl2());
  }
 
  static void initiateWorkFlow(WorkflowManager2 workflowMgr){
    System.out.println("Starting the workflow ... the old way");
    workflowMgr.doTask1();
    workflowMgr.doTask2();
    workflowMgr.doTask3();
    workflowMgr.doTask4();
  }
}

and the output would be...

Starting the workflow ... the old way
Doing Task1...
Doing Task2.1...
Doing Task3.1...
Doing Task4...
Starting the workflow ... the old way
Doing Task1...
Doing Task2.2...
Doing Task3.2...
Doing Task4...

So far so good. But the main intent of this post is not to create yet another blog post on Template Method pattern, but to see how we can leverage Java 8 Lambda Expression and Default Methods. I have already written before, that only interfaces which have Single Abstract Methods can be written as lambda expressions. What this translates to in this example is that, the WorkflowManager2 can only have one abstract/customizable task out of the 4 tasks.

So restricting to one abstract method is a major restriction and may not be applicable in many realtime scenarios. I dont wish to reiterate the same old Template Method pattern examples, instead my main intention of writing this is to show how lambda expressions and default methods can be leveraged in scenarios where you are dealing with abstract classes with single abstract methods.

If you are left wondering what these lambda expressions in java mean and also these default methods in java, then please spend some time to read about lambda expressions and default methods before proceeding further.

Instead of an abstract class we would use an interface with default methods, so our workflow system would look like:

interface WorkflowManager{
  public default void doTask1(){
    System.out.println("Doing Task1...");
  }
 
  public void doTask2();
 
  public default void doTask3(){
    System.out.println("Doing Task3...");
  }
 
  public default void doTask4(){
    System.out.println("Doing Task4...");
  }
}

Now that we have the workflow system with customisable Task2, we will go ahead and initiate some customised workflows using Lambda expressions…

public class TemplateMethodPatternLambda {
  public static void main(String[] args) {
    /**
     * Using lambda expression to create different
     * implementation of the abstract workflow
     */
    initiateWorkFlow(()->System.out.println("Doing Task2.1..."));
    initiateWorkFlow(()->System.out.println("Doing Task2.2..."));
    initiateWorkFlow(()->System.out.println("Doing Task2.3..."));
  }
 
  static void initiateWorkFlow(WorkflowManager workflowMgr){
    System.out.println("Starting the workflow ...");
    workflowMgr.doTask1();
    workflowMgr.doTask2();
    workflowMgr.doTask3();
    workflowMgr.doTask4();
  }
}

This is in a small way lambda expressions can be leveraged in the Template Method Pattern.

Template method pattern Template

Published at DZone with permission of Mohamed Sanaulla, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Automated Bug Fixing: From Templates to AI Agents
  • Dynamic File Upload Component in Salesforce LWC
  • Safeguarding Web Applications With Cloud Service Providers: Anti-CSRF Tokenization Best Practices
  • Make Your Backstage Templates Resilient

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!