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

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

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

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

  • Template Design Pattern or Template Method Design Pattern in Java
  • Unraveling Lombok's Code Design Pitfalls: Exploring Encapsulation Issues
  • Introduction To Template-Based Email Design With Spring Boot
  • Architecture and Code Design, Pt. 2: Polyglot Persistence Insights To Use Today and in the Upcoming Years

Trending

  • While Performing Dependency Selection, I Avoid the Loss Of Sleep From Node.js Libraries' Dangers
  • A Guide to Container Runtimes
  • Solid Testing Strategies for Salesforce Releases
  • Docker Model Runner: Streamlining AI Deployment for Developers
  1. DZone
  2. Coding
  3. Java
  4. Using Template Method Design Pattern In Java

Using Template Method Design Pattern In Java

Today, I will discuss another very useful design pattern named the Template Method Design Pattern. Read on to find out more!

By 
Brijesh Saxena user avatar
Brijesh Saxena
DZone Core CORE ·
Oct. 30, 20 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
9.9K Views

Join the DZone community and get the full member experience.

Join For Free

Today, I will discuss another very useful design pattern named the Template Method Design Pattern.

Template Method Design Pattern

  • The Template Method pattern is one of the behavioral design patterns identified by Gamma et al. in the book Design Patterns.
  • The Template Method pattern provides a method in a super-class, usually an abstract super-class, and defines the skeleton of an operation in terms of several high-level steps.
  • Generally, these steps are implemented by additional helper methods in the same class as the template method. 
  • The helper methods may be either created as an abstract method, for which sub-classes are required to provide concrete implementations, or hook methods, which have empty bodies in the super-class. 
  • The Template Method design pattern is used to define an algorithm as a skeleton of operations and leave the details to be implemented by the child classes.
  • In this way of implementation, the overall structure and sequence of the algorithm are preserved by the parent class.
  • The Template Method pattern defines the sequential steps to execute a multi-step algorithm. We can provide a default implementation as well.
  • In the Template Method pattern, we define a preset structure method called template method which consists of steps. 
  • These steps can be created as an abstract method which will be implemented by its sub-classes. 
  • In the Template Method pattern, an abstract class exposes defined way(s)/template(s) to execute its methods.
  • The template method uses and defines the sequence of steps to perform the algorithm.

abstract template class

Let's take an example to understand it better.

Car Manufacturing Example Using Template Method Design Pattern

I am using the same example I used for explaining the Builder Design Pattern to help you understand the difference between both.

First, we define an abstract class to represent a car manufacturing template. Here's the code for CarTemplate class:

Java
 




x
1
74


 
1
package org.trishinfotech.template;
2

          
3
public abstract class CarTemplate {
4

          
5
    protected String chassis;
6
    protected String body;
7
    protected String paint;
8
    protected String interior;
9

          
10
    public CarTemplate() {
11
        super();
12
    }
13

          
14
    // steps
15
    public abstract void fixChassis();
16

          
17
    public abstract void fixBody();
18

          
19
    public abstract void paint();
20

          
21
    public abstract void fixInterior();
22

          
23
    // template method
24
    public void manufactureCar() {
25
        fixChassis();
26
        fixBody();
27
        paint();
28
        fixInterior();
29
    }
30

          
31
    public String getChassis() {
32
        return chassis;
33
    }
34

          
35
    public void setChassis(String chassis) {
36
        this.chassis = chassis;
37
    }
38

          
39
    public String getBody() {
40
        return body;
41
    }
42

          
43
    public void setBody(String body) {
44
        this.body = body;
45
    }
46

          
47
    public String getPaint() {
48
        return paint;
49
    }
50

          
51
    public void setPaint(String paint) {
52
        this.paint = paint;
53
    }
54

          
55
    public String getInterior() {
56
        return interior;
57
    }
58

          
59
    public void setInterior(String interior) {
60
        this.interior = interior;
61
    }
62

          
63
    @Override
64
    public String toString() {
65
        // StringBuilder class also uses Builder Design Pattern with implementation of
66
        // java.lang.Appendable interface
67
        StringBuilder builder = new StringBuilder();
68
        builder.append("Car [chassis=").append(chassis).append(", body=").append(body).append(", paint=").append(paint)
69
                .append(", interior=").append(interior).append("]");
70
        return builder.toString();
71
    }
72

          
73
}
74

          



Here please notice that manufactureCar() method is a template method here. And methods fixChassis(), fixBody(), paint() and fixInterior() are the steps which will be defined by different sub-classes. The template method uses and defines the sequence of steps to perform the algorithm.

Now we will implement concrete sub-classes to define different flavors of templates.

Here's the code for ClassicCar class:

Java
 




xxxxxxxxxx
1
34


 
1
package org.trishinfotech.template;
2

          
3
public class ClassicCar extends CarTemplate {
4

          
5
    public ClassicCar() {
6
        super();
7
    }
8

          
9
    @Override
10
    public void fixChassis() {
11
        System.out.println("Assembling chassis of the classical model");
12
        this.chassis = "Classic Chassis";
13
    }
14

          
15
    @Override
16
    public void fixBody() {
17
        System.out.println("Assembling body of the classical model");
18
        this.body = "Classic Body";
19
    }
20

          
21
    @Override
22
    public void paint() {
23
        System.out.println("Painting body of the classical model");
24
        this.paint = "Classic White Paint";
25
    }
26

          
27
    @Override
28
    public void fixInterior() {
29
        System.out.println("Setting up interior of the classical model");
30
        this.interior = "Classic interior";
31
    }
32

          
33
}
34

          



Here's the code for ModernCar class:

Java
 




xxxxxxxxxx
1
34


 
1
package org.trishinfotech.template;
2

          
3
public class ModernCar extends CarTemplate {
4

          
5
    public ModernCar() {
6
        super();
7
    }
8

          
9
    @Override
10
    public void fixChassis() {
11
        System.out.println("Assembling chassis of the modern model");
12
        this.chassis = "Modern Chassis";
13
    }
14

          
15
    @Override
16
    public void fixBody() {
17
        System.out.println("Assembling body of the modern model");
18
        this.body = "Modern Body";
19
    }
20

          
21
    @Override
22
    public void paint() {
23
        System.out.println("Painting body of the modern model");
24
        this.paint = "Modern Black Paint";
25
    }
26

          
27
    @Override
28
    public void fixInterior() {
29
        System.out.println("Setting up interior of the modern model");
30
        this.interior = "Modern interior";
31
    }
32

          
33
}
34

          



Here's the code for SportsCar class:

Java
 




xxxxxxxxxx
1
34


 
1
package org.trishinfotech.template;
2

          
3
public class SportsCar extends CarTemplate {
4

          
5
    public SportsCar() {
6
        super();
7
    }
8

          
9
    @Override
10
    public void fixChassis() {
11
        System.out.println("Assembling chassis of the sports model");
12
        this.chassis = "Sporty Chassis";
13
    }
14

          
15
    @Override
16
    public void fixBody() {
17
        System.out.println("Assembling body of the sports model");
18
        this.body = "Sporty Body";
19
    }
20

          
21
    @Override
22
    public void paint() {
23
        System.out.println("Painting body of the sports model");
24
        this.paint = "Sporty Torch Red Paint";
25
    }
26

          
27
    @Override
28
    public void fixInterior() {
29
        System.out.println("Setting up interior of the sports model");
30
        this.interior = "Sporty interior";
31
    }
32

          
33
}
34

          



Now we will write our Main class to execute and test the output:

Java
 




xxxxxxxxxx
1
17


 
1
package org.trishinfotech.template;
2

          
3
public class Main {
4

          
5
    public static void main(String[] args) {
6
        CarTemplate car = new SportsCar();
7
        car.manufactureCar();
8
        if (car != null) {
9
            System.out.println("Below car delievered: ");
10
            System.out.println("======================================================================");
11
            System.out.println(car);
12
            System.out.println("======================================================================");
13
        }
14
    }
15

          
16
}
17

          



Below is the output:

Java
 




xxxxxxxxxx
1


 
1
Assembling chassis of the sports model
2
Assembling body of the sports model
3
Painting body of the sports model
4
Setting up interior of the sports model
5
Below car delievered: 
6
======================================================================
7
Car [chassis=Sporty Chassis, body=Sporty Body, paint=Sporty Torch Red Paint, interior=Sporty interior]
8
======================================================================
9

          



Well, there you have it! I hope this tutorial helped to understand the Template Method pattern.

Source Code can be found here: Template-Method-Design-Pattern-Source-Code

Liked the article? Please don't forget to press that like button. Happy coding!

Template Design Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Template Design Pattern or Template Method Design Pattern in Java
  • Unraveling Lombok's Code Design Pitfalls: Exploring Encapsulation Issues
  • Introduction To Template-Based Email Design With Spring Boot
  • Architecture and Code Design, Pt. 2: Polyglot Persistence Insights To Use Today and in the Upcoming Years

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!