“If you want to go fast, go alone. If you want to go far, go together”. - African Proverb.

Template method pattern is used when we have multiple algorithms that have some common functionality. In general words, the template is like a default structure for doing a specific task. we are using this pattern for the architectural plans and throughout the engineering domain. A template plan can be built on with further variations. From the book, the main intent is like

Defines the skeleton of an algorithm in a method, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.

We can think about a situation where we are building a solution for the ordering process. We can order online or by going to the store itself. Every order has some common business, we have to collect items from the store, then we have to make a payment and eventually we have to deliver the order to the specific customer. There is an extra additional business is, sometimes the customer wants to wrap their product for sending as a gift. So, we took all the common business in a single method that will be work as a template method.

Coding Implementation:

// abstract template class 
public abstract class OrderProcessTemplate {
public boolean isGift;
public abstract void doSelect();
public abstract void doPayment();

public final void giftWrap(){
try
{
System.out.println("Gift wrap successful");
}
catch (Exception e)
{
System.out.println("Gift wrap unsuccessful");
}
}
public abstract void doDelivery();
public final void processOrder(boolean isGift){
doSelect();
doPayment();
if(isGift){
giftWrap();
}
doDelivery();
}

}
// Order from the store public class StoreOrder extends OrderProcessTemplate{
@Override
public void doSelect() {
System.out.println("Customer chooses the item from shelf.");
}

@Override
public void doPayment() {
System.out.println("Pays at counter through cash/POS");
}

@Override
public void doDelivery() {
System.out.println("Item delivered to in delivery counter.");
}
}
// Order through the online
public class NetOrder extends OrderProcessTemplate{
@Override
public void doSelect() {
System.out.println("Item added to the online shopping cart");
System.out.println("Get gift wrap preference");
System.out.println("Get delivery address.");
}

@Override
public void doPayment() {
System.out.println
("Online Payment through Netbanking, card or Paytm");
}

@Override
public void doDelivery() {
System.out.println
("Ship the item through post to delivery address");
}
}
// Final Client Class to invoke our ordering system
public class TemplateMethodPatternClient {
public static void main(String[] args) {
OrderProcessTemplate netOrder = new NetOrder();
netOrder.processOrder(true);
System.out.println();
OrderProcessTemplate storeOrderProcessTemplate = new StoreOrder();
storeOrderProcessTemplate.processOrder(true);
}
}
UML Diagram

The abstract class should contain the template method, which should be made final so that it cannot be overridden. This template method makes use of other operations available in order to run the algorithm but is decoupled for the actual implementation of these methods. All operations used by this template method are made abstract, so their implementation is deferred to subclasses. The concrete classes implement all the abstract methods written in the abstract class.

The template pattern makes us remember about the Hollywood Principle, “Don’t call us we will call you”. The template method in the parent class controls the overall process, “calling” subclass methods when necessary. The Hollywood principle avoids low-level components depending on high-level components and instead gives these low-level classes (ConcreteClass) a way of hooking into the parent class (AbstractClass). Hence, it supports the Dependency inversion principle.

This Pattern supports the open-closed principle by adding another order process as a concrete class. It also serves the singular responsibility principle. It might violate the Liskov substitution principle by suppressing a default step implementation via a subclass.

Relation with another design principle:

  1. It looks like the strategy pattern but the strategy pattern selects the algorithm at the run time and works at the object level on the other side the Template method selects the algorithm at compile time so works at a class level.
  2. It has a relation with the factory method, which is the specialization of the template method.

References :

  1. https://www.geeksforgeeks.org/template-method-design-pattern/
  2. Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. Design patterns: elements of reusable object-oriented software. Addison-Wesley Professional, 1995.
  3. https://github.com/abdullahalnoman8/software_architecture_code_sample/tree/main/src/com/softwaredesignpatterns/template_pattern/example_1

Software Engineer | High Integrity System Graduate @Frankfurt University of Applied Sciences

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store