Java Template Design Pattern Example
1. Introduction to Java Template Design Pattern
In this post, we will discuss and elobarate the java template design pattern in detail. Java Template design pattern is one of the important behavioral design pattern. Template design pattern describes algorithm steps and can provide default implementations common to most or all of the subclasses. Let’s get an example to understand and learn Template design pattern, if we want to construct a house or flat by an algorithm. To construct a flat or house, construction of pillars, construction of building walls and windows are the steps to be taken for construction. The most important point is that the execution order can’t be changed because before building the house we can not build the windows. Then we can use different methods to build the house for a template method.
Now, for every type of house, whether a house with boards or a glass house, the foundation is the same. So if subclasses wish to override this method, we can provide the basic implementation for this, but it’s mostly common for all house types.
In other words, the template method design pattern shall define an algorithm as an operational skeleton and leave the details for the child classes. And parent class preserves the overall structure and sequence of the algorithm.
This article explains the design models available and follows a real world example of the template design pattern. This could help to clarify precisely when the java template design pattern is used. We will then learn how to plan the code to implement a template design pattern.
2. Types of Java Design Patterns
For software developers design patterns are very popular. A design pattern is an excellent solution to a common issue with software. Design patterns already have been defined and provide the industry standard approach for the possible solution of a recurrent problem. Java Design Patterns are divided into three categories – creational, structural, and behavioral design patterns.
2.1 Creational Pattern
The best way to create an object is through its reuse and modificability, are defined in all creational design patterns. The best way to handle instantiation is described. Hard coding is a flaw and should be avoided if the reuse and modificability of the instantiation is desired. We can use patterns in these scenarios to make this approach more general and flexible.
- Factory Pattern
- Abstract Factory Pattern
- Singleton Pattern
- Prototype Pattern
- Builder Pattern.
2.2 Structural Pattern
Structural Patterns define how really objects, classes and structures can be combined. Then we really differentiate between patterns of objects and classes. The major difference is that class patterns are described by inheritance in relation and structure. Object patterns, on the other hand, describe how objects can be combined to form larger structures that are more complex.
- Adapter Pattern
- Bridge Pattern
- Composite Pattern
- Decorator Pattern
- Facade Pattern
- Flyweight Pattern
- Proxy Pattern
2.3 Behavioral Pattern
Behavioral design patterns are patterns concentrating on relationships among cooperative objects. The relationships between cooperating objects ought to be such that they interact while keeping the connection as loosely as possible. The loose connection is the main feature of n-tier architectures. To prevent hard coding and dependencies, the implementation and the customer should be loosely linked.
- Chain Of Responsibility Pattern
- Command Pattern
- Interpreter Pattern
- Iterator Pattern
- Mediator Pattern
- Memento Pattern
- Observer Pattern
- State Pattern
- Strategy Pattern
- Template Pattern
- Visitor Pattern
In this article, we are going to discuss the java template design pattern by taking a real world example. When two or more implementations of similar algorithms exist, the Template Method pattern is used. Templates in the real world are always used for construction plans and in the entire engineering field. A template plan can be defined and further variations can be added. For instance, there can be many variations in a basic plan such as adding extensions or using another heating system.
3. Template Design Pattern – Real life example
In this section, we will see a real world example using java template method design pattern. The example explains how the template method is used to manage algorithms, relationships and responsibilities between objects. Here we will take an example of coffee making process for understanding the template method.
The following image explains the procedure or steps of how coffee can be made by anyone. The coffee presented in the below image are only for the understanding purpose and there is no direct relation with any company.
As shown in the image, suppose we want to make a bru coffee for one of our guest. The making of bru coffee includes boiling water, adding milk, adding sugar as required and then finally adding bru coffee to it. Let’s suppose some another guest demanded for nescafe coffee instead of bru coffee. The process consists of boiling water, adding milk, adding sugar as needed and at last adding nescafe coffee. So, from the above example we came to know that the procedure or steps for making both the coffee (Bru Coffee or Nescafe Coffee) are same.
Since, the process of preparing coffee is same and just the adding of coffee powder part or step is based on guest demand so, for that we can do one thing is we will create a template method called prepareCoffee() and inside this method we will define the steps for making the coffee either bru coffee or nescafe coffee such as Boil water, Add milk, Add sugar and Add CoffeePowder. By using this template method we can make any flavour or any type of coffee. Hence, we can consider this example is a best real life example to understand Template design pattern.
4. Implementing Template Design Pattern
In this section we will comprehend how Tempalte design pattern works in java program. We are taking an example of how different types of houses or flats are build using tempalte design pattern by implementing this pattern in java.
PrepareHouse.java
public abstract class PrepareHouse { // Template method is final so subclasses can't override public final void constructHouse() { construcFoundation(); construcPillars(); construcWalls(); construcWindows(); System.out.println("House is constructed."); } // Methods to be implemented by subclasses public abstract void construcFoundation(); public abstract void construcPillars(); public abstract void construcWalls(); public abstract void construcWindows(); }
In the above code, we have created an abstract class known as PrepareHouse in which we have defined a final template method called constructHouse(). Inside this template method we called for methods such as construcFoundation(), construcPillars(), construcWalls(), construcWindows(). Further, we have defined four abstract methods which are called inside the template method.
House.java
public class House extends PrepareHouse { @Override public void constructFoundation() { System.out.println("Constructing Foundation with cement,iron rods and sand"); } @Override public void constructPillars() { System.out.println("Constructing Pillars for house"); } @Override public void constructWalls() { System.out.println("Constructing Walls for house"); } @Override public void constructWindows() { System.out.println("Constructing Windows for house"); } }
In the above code, we created House class which extends PrepareHouse class. In this class we have implemented all the four abstract classes constructFoundation(), constructPillars(), constructWalls(), constructWindows().
Flat.java
public class Flat extends PrepareHouse { @Override public void constructFoundation() { System.out.println("Constructing Foundation with cement,iron rods and sand"); } @Override public void constructPillars() { System.out.println("Constructing Pillars for flat"); } @Override public void constructWalls() { System.out.println("Constructing Walls for flat"); } @Override public void constructWindows() { System.out.println("Constructing Windows for flat"); } }
So, here we have created Flat class which extends PrepareHouse class. In this class we have implemented all the four abstract classes constructFoundation(), constructPillars(), constructWalls(), constructWindows().
Tenament.java
public class Tenament extends PrepareHouse { @Override public void constructFoundation() { System.out.println("Constructing Foundation with cement,iron rods and sand"); } @Override public void constructPillars() { System.out.println("Constructing Pillars for tenament"); } @Override public void constructWalls() { System.out.println("Constructing Walls for tenament"); } @Override public void constructWindows() { System.out.println("Constructing Windows for tenament"); } }
Similarly, here we have created Tenament class which extends PrepareHouse class. In this class we have implemented all the four abstract classes constructFoundation(), constructPillars(), constructWalls(), constructWindows().
TemplateDesignPattern.java
public class TemplateDesignPattern { public static void main(String[] args) { System.out.println("Constructing a House\n"); PrepareHouse house = new House(); house.constructHouse(); System.out.println("**********************************************"); System.out.println("Constructing a Flat\n"); house = new Flat(); house.constructHouse(); System.out.println("**********************************************"); System.out.println("Constructing a Tenament\n"); house = new Tenament(); house.constructHouse(); } }
In the above code, we have created a TemplateDesignPattern class which consists of main() method. In this main() method we have created objects of House, Flat and Tenament classes and called constructHouse() method using this three objects.
Constructing a House Constructing Foundation with cement,iron rods and sand Constructing Pillars for house Constructing Walls for house Constructing Windows for house House is constructed. ********************************************** Constructing a Flat Constructing Foundation with cement,iron rods and sand Constructing Pillars for flat Constructing Walls for flat Constructing Windows for flat House is constructed. ********************************************** Constructing a Tenament Constructing Foundation with cement,iron rods and sand Constructing Pillars for tenament Constructing Walls for tenament Constructing Windows for tenament House is constructed.
Form the output, we understood that we can construct House, Flat or Tenament using the tempalte method itself and we don’t need to create sepearate methods for the creation of House, Flat or Tenament.
5. Benefits of Template Design Pattern
In this section, we will discuss some of the advantages of Template design pattern. The advantages are as follows:
- It lowers the application’s boiler codes by reuse of the code.
- This model creates a template or way of reusing several similar algorithms to fulfill business needs.
- There is no duplication of code, as we saw previously in the implementation of Template pattern in java code.
- The reuse of codes occurs using the Template Method pattern because it uses inheritance and not composition. There are only a few methods to override.
- Subclasses can decide how to introduce the steps in an algorithm with mobility.
- Helps us when we wish clients to probably extend the algorithm only by a specific step but not by the whole or structure of the algorithm.
- The duplicate code can be pulled into a superclass.
6. Conclusion
From the above discussion it is concluded that the Template design pattern provides an abstract class with a defined way of performing its methods or templates. Its subclasses may be necessary to override the method implementation, but the invocation shall be defined in the same way as an abstract class and hence this pattern is classified as a behavioral design pattern.
7. Download the Project
You can download the project files for the above example from the below link:
You can download the full source code of this example here: TemplateDesignPattern.zip