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

  • Template Design Pattern or Template Method Design Pattern in Java
  • Architectural Evidence in Enterprise Java: Making Domain-Driven Design Visible
  • Unraveling Lombok's Code Design Pitfalls: Exploring Encapsulation Issues
  • Introduction To Template-Based Email Design With Spring Boot

Trending

  • DZone's Article Submission Guidelines
  • DevOps Is Dead, Long Live Platform Engineering
  • Mocking Kafka for Local Spring Development
  • Retesting Best Practices for Agile Teams: A Quick Guide to Bug Fix Verification
  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
·
Oct. 30, 20 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
10.4K 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
  • Architectural Evidence in Enterprise Java: Making Domain-Driven Design Visible
  • Unraveling Lombok's Code Design Pitfalls: Exploring Encapsulation Issues
  • Introduction To Template-Based Email Design With Spring Boot

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