Wednesday, July 13, 2022

Behavioral Design Patterns # Template Method

Template Method is a behavioral design pattern that defines the skeleton of an algorithm in the superclass but lets subclasses override specific steps of the algorithm without changing its structure.


Problem

Imagine that you’re creating a data mining application that analyzes corporate documents. Users feed the app documents in various formats (PDF, DOC, CSV), and it tries to extract meaningful data from these docs in a uniform format.

The first version of the app could work only with DOC files. In the following version, it was able to support CSV files. A month later, you “taught” it to extract data from PDF files.



At some point, you noticed that all three classes have a lot of similar code. While the code for dealing with various data formats was entirely different in all classes, the code for data processing and analysis is almost identical. 

Wouldn’t it be great to get rid of the code duplication, leaving the algorithm structure intact?

There was another problem related to client code that used these classes. It had lots of conditionals that picked a proper course of action depending on the class of the processing object. 


If all three processing classes had a common interface or a base class, you’d be able to eliminate the conditionals in client code and use polymorphism when calling methods on a processing object


Solution


The Template Method pattern suggests that you break down an algorithm into a series of steps, turn these steps into methods, and put a series of calls to these methods inside a single template method. 

The steps may either be abstract, or have some default implementation. To use the algorithm, the client is supposed to provide its own subclass, implement all abstract steps, and override some of the optional ones if needed (but not the template method itself).

Let’s see how this will play out in our data mining app. We can create a base class for all three parsing algorithms. This class defines a template method consisting of a series of calls to various document-processing steps


At first, we can declare all steps abstract, forcing the subclasses to provide their own implementations for these methods. In our case, subclasses already have all necessary implementations, so the only thing we might need to do is adjust signatures of the methods to match the methods of the superclass.

Now, let’s see what we can do to get rid of the duplicate code. It looks like the code for opening/closing files and extracting/parsing data is different for various data formats, so there’s no point in touching those methods. 

However, implementation of other steps, such as analyzing the raw data and composing reports, is very similar, so it can be pulled up into the base class, where subclasses can share that code.

As you can see, we’ve got two types of steps:

  • abstract steps must be implemented by every subclass
  • optional steps already have some default implementation, but still can be overridden if needed

There’s another type of step, called hooks. A hook is an optional step with an empty body. A template method would work even if a hook isn’t overridden. 


Usually, hooks are placed before and after crucial steps of algorithms, providing subclasses with additional extension points for an algorithm.



Structure




Template Method Design Pattern Example

suppose we want to provide an algorithm to build a house. The steps need to be performed to build a house are – building foundation, building pillars, building walls and windows. 

The important point is that the we can’t change the order of execution because we can’t build windows before building the foundation. So in this case we can create a template method that will use different methods to build the house.

Now building the foundation for a house is same for all type of houses, whether its a wooden house or a glass house. So we can provide base implementation for this, if subclasses want to override this method, they can but mostly it’s common for all the types of houses.

To make sure that subclasses don’t override the template method, we should make it final.

Template Method Abstract Class

Since we want some of the methods to be implemented by subclasses, we have to make our base class as abstract class.

public abstract class HouseTemplate { //template method, final so subclasses can't override public final void buildHouse(){ buildFoundation(); buildPillars(); buildWalls(); buildWindows(); System.out.println("House is built."); } //default implementation private void buildWindows() { System.out.println("Building Glass Windows"); } //methods to be implemented by subclasses public abstract void buildWalls(); public abstract void buildPillars(); private void buildFoundation() { System.out.println("Building foundation with cement,iron rods and sand"); } }
Template Method Concrete Classes
We can have different type of houses, such as Wooden House and Glass House.

public class WoodenHouse extends HouseTemplate { @Override public void buildWalls() { System.out.println("Building Wooden Walls"); } @Override public void buildPillars() { System.out.println("Building Pillars with Wood coating"); } }

We could have overridden other methods also, but for simplicity I am not doing that.
public class GlassHouse extends HouseTemplate { @Override public void buildWalls() { System.out.println("Building Glass Walls"); } @Override public void buildPillars() { System.out.println("Building Pillars with glass coating"); } }

Template Method Design Pattern Client

Let’s test our template method pattern example with a test program.

public class HousingClient { public static void main(String[] args) { HouseTemplate houseType = new WoodenHouse(); //using template method houseType.buildHouse(); System.out.println("************"); houseType = new GlassHouse(); houseType.buildHouse(); } }

Notice that client is invoking the template method of base class and depending of implementation of different steps, it’s using some of the methods from base class and some of them from subclass.

Output of the above program is:

Building foundation with cement,iron rods and sand Building Pillars with Wood coating Building Wooden Walls Building Glass Windows House is built. ************ Building foundation with cement,iron rods and sand Building Pillars with glass coating Building Glass Walls Building Glass Windows House is built.

You may also like

Kubernetes Microservices
Python AI/ML
Spring Framework Spring Boot
Core Java Java Coding Question
Maven AWS