Template Design Pattern in Java

The Template Method Design Pattern in Java is an important design pattern that belongs to the group of Behavioural design patterns. This pattern is commonly used whenever a certain algorithm of method creation has to be defined and made a skeleton such that other subclasses can inherit the methods and extend their functionalities and usability.

In computing terminology, template refers to a preset format or framework (behavioural structure) that files and documents should conform to. In this case, the Template Method Pattern provides a set structure for methods to be created centring the base algorithm.

Definition

By definition, the Template Method Pattern is a Behavioural Design Pattern that provides a particular skeleton for methods to be created in a super class. Sub classes can extend the method template and work to add features without duplicating the code.

Structure

  • Abstract Class – This is the super class that will contain the template method. This method will then be extended to the sub classes. It is generally good coding practice if the template method is demarcated as final so that it is not overridden.
  • Sub Classes (Concrete Classes) – This is where the actual implementation takes place. Concrete classes extend the template method from the super class.

Example and Code

The following is a pseudo code. In this example, let us assume we are decorating a Christmas tree. Several decorations can be applied on the Christmas tree to make it look beautiful. Here we will be using the Template Method to decorate. The individual decorations will use this template thereafter.

//This is the main class that will contain the template method

public abstract class ChristmasTreeDecor {

public final Tree decorateTree() {
decorLED ();
decorSantaBauble();
decorCandy();
decorShimmeringBall();
return new Tree(treeDecor);
}

public abstract void decorLED()
System.out.println(“LED lights added”);

public abtract void decorSantaBauble()
System.out.println(“Santa Bauble added”);

public abstract void Candy()
System.out.println(“Candy added”);

public abstract void ShimmeringBall()
System.out.println(“Shimmering Balls added”);
}

//The template method has been declared final so that is is not overridden during method call.

When to use the Template Design Pattern?

This method pattern is commonly used in frameworks where several subclasses extend various methods to perform different operations. If you want to make sure your code has a fixed algorithm in the super class and the functionalities in the sub classes, this design pattern is your go-to.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.