Behavioral – Template Design Pattern
August 22, 2020 1 min read

Template pattern is a behavioral design pattern that defines the skeleton of an algorithm in an operation, deferring some steps to client subclasses. The overall structure and sequence of the algorithm is preserved by the parent class. In the template method pattern, we have a preset structure method called template method which consists of steps. These steps can be abstract methods which will be implemented by its subclasses.
Let’s see an example to understand better about template design pattern.

The “OrderTemplate” class is an abstract class containing the algorithm skeleton. As shown on program, “processOrder()” is the method that contains the process steps.

Here “OnlineOrder” is a subclass that extends the parent class “OrderTemplate” and using the overall algorithm used to process an order is defined in the parent class.

This is also same as the sub class “OnlineOrder”. “StoreOrder” sub class also has the same order processing steps.
But the way individual operations are performed vary depending on the subclass.
Let’s see the main method.

It is simple as you can see that only two objects are created to call the method to process the order.
Output:

This behavioral design pattern is one of the easiest to understand and implement. Template design pattern is used popularly in framework development. This helps to avoid code duplication also.
You can visit the below given articles to learn about creational design patterns and Structural Design Patterns.
Thank you.
Creational Design Patterns
Abstract Factory Design Pattern
Structural Design Patterns


