jobs4timesLogo jobs4timesLogo

Template Method Design Pattern

  • Template method design pattern is a behavioral pattern of the Gang Of Four(GOF) design patterns catalog.
  • In this pattern we have a base template method; it defines an algorithm with some abstract steps.
  • These steps have to be implemented by sub-classes.

  • For example I have a class called DataRenderer this class is responsible to rendering the data to output console.
  • But to render the data first we need to read and process it.
  • So we have a methods like readData() and processData().
  • But these methods will be declared as abstract as there are multiple sources from which you can read the data and multiple ways we can process it.
  • But to render the data you need to read and process it, so the algorithm for render() is fixed which is read and process but how to read, from where to read and how to process is left to the sub-classes to handle.
package design;

public abstract class DataRenderer{
 
 //algorithm is fixed
 public void render(){
	 String data=null;
	 String pData=null;
	 
	 data=readData();
	 pData=processData(data);
	 
	 System.out.println(pData);
 }

 public abstract String readData();
 public abstract String processData(String data);
}
package design;

public class XMLDataRenderer extends DataRenderer {

 @Override
 public String readData() {
  return "xml data";
 }

 @Override
 public String processData(String data) {
  return "processed "+data;
 }

}
package design;

public class TextDataRenderer extends DataRenderer {

 @Override
 public String readData() {
  return "text data";
 }

 @Override
 public String processData(String data) {
  return "processed "+data;
 }

}
  • In the above example the responsibilities of reading and processing has been left to sub-classes.
  • render() method remains same calling the methods of your sub-classes.
Now if a client wants to reader the data, he/she has to create the object of XMLDataRender or TextDataRender and has to call the render() method which delegates the call to readData() and processData() as per the algorithm to render it.
package design;

public class TemplateMethodTest {

public static void main(String[] args){
 DataRenderer renderer=new XMLDataRenderer();
 renderer.render();
}

}
The Template method we declare in the base class cannot be overridden as the algorithm is fixed, and the sub-classes should not change the behavior of it we need to declare it as final.

public final void render()
The UML representation of the pattern :
template-method-design-pattern
Key points :
  • The template method in the super class calls the methods of the sub-classes, instead the sub-classes calls the template method of the super class.

  • Template methods are techniques for code reuse because with this you can standardize the algorithm and defer the specific implementations to the sub-classes. Again the sub-classes do need to re-write the same algorithm.


BACK