Wednesday, April 19, 2023

Template Method Design Pattern in Java? Example Tutorial

Template Method Pattern defines a sequence of steps of an algorithm but let you free to implement those steps on your way. You cannot change the algorithm but you can define how those steps should behave. To make sure that you cannot change the algorithm, template methods are usually made final in Java, which is also a good use case of when to make a method final in Java. The subclasses are still  allowed to override the steps but as I said, they are not allowed to change the sequence. It can also be provided a default implementation for one or more steps. Let us look at the following example to understand Template Method Pattern.  A Template method pattern provides a skeleton for performing any sort of algorithm or an operation, and it allows the sub-classes to re-define part of the logic

One of the key advantage of Template pattern is that its natural fit for building frameworks, so that parent framework classes can make callbacks into methods implemented in children. Spring Framework makes full examples of Template pattern and you will find several key classes like JdbcTemplate, RestTemplate, and JmsTemplate which are created using Template pattern.

Here are few more examples of Tempalte method pattern from JDK and other popular libraries: 

Examples:
  • java.util.AbstractList
  • Servlet's doGet and doPost methods
  • MDB's onMessage method
  • Struts Action class
  • Spring's data access classes
  • Spring's RestTemplate class
  • Cons: Restricts you to a single inheritance in Java.

t you don't see the pattern doesn't mean that HttpServlet and AbstractList are not good examples. With HttpServelt, subclasses do implement doGet, doPost, etc which are the extensions points called in service (which is the only method called by the container for each request as per spec). With AbstractList, subclasses do implement get, size, set, remove (just look at the javadoc header) which are the extension points.

What problem does Template Method Pattern solve? Intent?

Template pattern Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. The method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure

Abstract classes and the Template Method pattern go very much hand-in-hand. An abstract class is a
superclass that defines the behavior of the classes in its hierarchy while deferring the implementation
details to its subclasses.

The superclass is abstract because it does not implement all of the behavior it
defines. The subclasses are concrete because each one implements all of the behavior, either by
inheriting it from its super classes or implementing the behavior itself

participants Abstract class Defines abstract primitive operations that concrete subclasses define to implement steps of an algorithm. Implements a template method defining the skeleton of an algorithm. The template method calls primitive operations as well as operations defined in AbstractClass or those of other objects. 

The concrete class implements the primitive operations to carry out subclass-specific steps of the algorithm.

6. Implementation Issues Operations that must be overridden by a subclass should be made abstract If the template method itself should not be overridden by a subclass, it should be made final In a template method, the parent class calls the operations of a subclass and not the other way around. This is an inverted control structure that's s sometimes referred to as the Hollywood principle as in, " Don't call us, we'll call you"

Template methods are extremely common.
  • Use them to cleanly factor the commonality among subclasses so as to avoid duplicating code.
  • Use them to provide "hooks" at well-defined points.
  • Note that template methods just let part of an algorithm vary, while strategies vary the whole algorithm.
Then in the same class, we define abstract methods brew() and addCondiments(), so the sub-classes have to implement them. We remove overwritten prepareRecipe() methods from Coffee and Tea classes and implement there only those two new methods



Advantages
The examples show how to encapsulate a piece of algorithms so the sub-classes can hook themselves right into computation any time they want. We learn a new design principle too!

Disadvantages
While Template method pattern is quite useful there is no pattern which only has advantages and no disadvantages. Similarly, Template pattern also has few disadvantages like at times debugging and understanding the sequence of flow can be confusing. 

Another disadvantage of Template patter is that maintenance of the template framework can be a problem as changes at any level (low-level or high-level) can disturb the implementation


Adding Hooks using Template Pattern

After learning the definition and diagram we read about the pretty common practice of using hooks methods together with the template method pattern. Hooks are methods injected into our template method to make it more flexible/extensible. 


Template Method Pattern in Java with Example - Tutorial


Going back to our coffee and tea example a hook could be added to prepareRecipe() method and depending on its result the addCondiments() method would be executed. New parent class code written in this way looks like:

After an introduction to hooks were presented with another design principle: The Hollywood Principle. This time it's pretty easy to remember: "Don't call us, we'll call you". It helps us with preventing "dependency rot" in our code-base. 

Dependency rot happens when high-level class is depending on low-level classes which are depending on sideways components which are depending on low-level classes, and so on. When rot sets in, no one can easily tell the way a system is designed.
 
With the new principle, we allow low-level components to hook themselves into a system, but high-level components determine when they are needed, and how. How does it work in our template method example? CaffeineBeverage has control over the algorithm for the recipe and calls on the sub-classes when they are needed for an implementation of a method. 

This class is our high-level component which tells Coffee and Tea classes Don't call us, we'll call you. 

The sub-classes never call the abstract class directly. Clients of beverages will depend only on CaffeineBeverage abstraction rather than concrete sub-classes. And this is how we reduce dependencies in the overall system.


Template Method Examples from JDK

After the new design principle authors show more examples of template method pattern implementations in Java. Not all of them depend on inheritance. There is an example with the Comparable interface and compareTo() template method. 

The Java Arrays class is responsible for different arrays manipulation such as sorting. Arrays class implements all required steps of sorting but it lets other classes decide on how elements are compared to each other.
 
The other two Java examples are examples of different classes and their hooks. JFrame class and its paint() hook method and Applet class with several hooks:
  • init() allows the applet to do whatever it wants to initialize the applet the first time,
  • start() allows the applet to do something when the applet is just about to be displayed on the web page,
  • stop() if the user goes to another page the stop() hook is used and the applet can do whatever it needs to do to stop its actions,
  • destroy(),
  • paint().
Spring Framework also have many examples of using Template pattern which greatly simplified coding. It has classes like JdbcTemplate, JmsTemplate, and RestTemplate which you can use to perform database, messaging, and REST related tasks with ease without worrying about implementing many boiler plate methods. 


How to implement Template Method Design Pattern in Java? Example

Now that we have understood what is Template method pattern is and what benefits it offers, it's time to learn how to implement the template method pattern in Java. Here is a complete code example you can copy, paste and tweak to use in your code. 
 
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
/**
* An example of Template method design pattern in Java.
*
* @author
*/
public class TemplatePatternDemo{
 
    public static void main(String args[]) {
        System.out.println("Making tea using template method pattern");
        CaffeineBeverageTemplate template = new Tea();
        template.prepareRecipe();
 
        System.out.println("Making coffie using template method");
        template = new Coffie();
        template.prepareRecipe();
    }
 
}
 
abstract class CaffeineBeverageTemplate {
 
    public final void prepareRecipe() {
        boilWater();
        brew();
        pourInCup();
        if (isCondimentRequested()) {
            addCondiments();
        }
    }
 
    public void boilWater() {
        System.out.println("Boiling water");
    }
 
    public abstract void brew();
 
    public void pourInCup() {
        System.out.println("Pouring in Cup");
    }
 
    public abstract boolean isCondimentRequested();
 
    public abstract void addCondiments();
}
 
class Tea extends CaffeineBeverageTemplate {
 
    @Override
    public void brew() {
        System.out.println("Brewing tea leaves");
    }
 
    @Override
    public boolean isCondimentRequested() {
        return false;
    }
 
    @Override
    public void addCondiments() {
    }
 
}
 
class Coffie extends CaffeineBeverageTemplate {
 
    @Override
    public void brew() {
        System.out.println("Brewing coffie beans");
 
    }
 
    @Override
    public boolean isCondimentRequested() {
        return true;
    }
 
    @Override
    public void addCondiments() {
        System.out.println("Adding some cream");
    }
 
}
 
 
Output
Making tea using template method pattern
Boiling water
Brewing tea leaves
Pouring in Cup
Making coffee using the template method
Boiling water
Brewing coffee beans
Pouring in Cup
Adding some cream


That's all about the Template method design pattern in Java. This is one of the important pattern to learn for Java developer as its quite useful. You will find many example of Template pattern in Spring Framework like JdbcTemplate, JmsTemplate, RestTemplate which are very useful classes and they all are created using Template method pattern.


Other Java Design Patterns tutorials you may like
  • 5 Free Courses to learn Object Oriented Programming (courses)
  • How to design a Vending Machine in Java? (questions)
  • Difference between Factory and Dependency Injection Pattern? (answer)
  • How to implement a Decorator design pattern in Java? (tutorial)
  • When to use Command Design Pattern in Java (example)
  • 20 System Design Interview Questions (list)
  • 7 Best Courses to learn Design Pattern in Java (courses)
  • How to implement the Strategy Design Pattern in Java? (example)
  • 18 Java Design Pattern Interview Questions with Answers (list)
  • How to create thread-safe Singleton in Java (example)
  • 7 Best Books to learn the Design Pattern in Java? (books)
  • Difference between Factory and Abstract Factory Pattern? (example)
  • Difference between State and Strategy Design Pattern in Java? (answer)
  • 5 Free Courses to learn Data Structure and Algorithms (courses)
  • 10 OOP Design Principle Every Java developer should learn (solid principle)
  • How to use Factory method design pattern in Java? (tutorial)
  • 7 Books to learn System Design for Beginners (System design books)
  • How to use Composite Design Pattern in Java (composite example)

Thanks a lot for reading this article so far. If you like this example and tutorial of Template Design Pattern in Java then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

P. S. - If you are an experienced Java developer and want to master object oriented design patterns and looking for a best design pattern resources like books and online courses then you can also checkout this list of best design pattern courses for experience developers to start with. It contains great online courses to learn design pattern and how to use them in real world coding. 

No comments:

Post a Comment