Template Method Design Pattern

This tutorial explain the basic concept of template method design pattern and how to use them. This is one of the pattern I have published as part of our Design pattern in Java series. If you are interested in receiving updates, please subscribe our newsletter.

What is Template Method Design Pattern?

Template Method Design Pattern

An abstract class defines various methods and has one non-overridden method which calls the various methods.

also read:

Wikipedia Says:

A template method defines the program skeleton of an aligorithm.The aligorithm itself is made abstract,and the subclasses override the abstract methods to provide concrete behavior.First a class is created that provides the basic steps of an aligorithm design.These steps are implemented using abstract methods.Later on subclasses change the abstract methods to implement real actions.Thus the general aligorithm is saved in one place but the concrete steps may be changed by the subclasses.
Non-Abstract Methods are completly controlled by the Template Method.In contrast the template method need not be changed and is not an abstract operation and thus may guarentee required steps before and after the abstract operations.Thus the template method is invoked and as a consequence the non-abstract methods and abstract methods are called in the correct sequence.

Why Template Method?

Define the skeleton of an aligorithm in an operation,deferring some steps to subclasses.Template methods lets subclasses redefine certain steps of an aligorithm without changing the aligorithm structure .[DesignPatterns, p. 325]

Sometimes we want to specify the order of operations that a method uses,but allow sub-classes to provide their own implementation of some of these operations.When ever we see two methods in subclasses,it makes sense to bring the methods together into a superclass method.

When Template Method?

Use the Template method pattern:

  • To implement the invariant parts of an algorithm once and leave it up to sub-classes to implement the behavior that can vary.
  • To localize common behavior among subclasses and place it in a common class(in this case a superclass) to avoid code duplication.This is a classic example of “code refactoring”.
  • To control how subclasses extend superclass operations.You can define a template method that calls “hook” operations at specific points,there by permitting extensions only at that point.


Two different component have significant similarities,but demonstrate no reuse of common interface or implementation.If a change common to both components becomes necessary,duplicate effort must be expended.

The component designer decides which steps of an aligorithm are invariant(or standard) and which are variant(or customizable).The invariant steps are implemented in an abstract base class,while the variant steps are either given a default implementation or no implementation at all.The “variant” steps represent “hooks”,or “placeholders” that can or must be supplied by the component’s client in a concrete derived class.
The component designer mandates the required steps of an aligorithm,and the ordering of the steps,but allow the component client to extend or replace some number of steps.
Template methods are prominently used in frameworks.Each framework implements the invariant pieces of domain’s architecture,and defines “placeholders” for all necessary or interesting client customization options.The inverted control structure has been affectionately labelled “the hollywood principle” – Don’t call us we will call you.

The template method is used to:

  • Let subclasses implement behavior that can vary.
  • Avoid duplication in the code.We look for general code in the aligorithm and implement variants in the subclasses.
  • Control at what point(s) subclassing is allowed.

Implementation Issues:

  • Operations which must be overridden by subclasses should be made abstract.
  • If the template method itself should not be overidden by subclasses it should be made final.
  • To allow a subclass to insert code at a specific spot in the operation of the aligorithm,insert “hook” operations into the template method.These hook operations may do nothing by default.
  • Try to minimize the number of operations that a subclass must override.
  • In a template method parent class calls the operations of a subclass and not the other way round.

The template method defines a skeleton of an aligorithm in an operation and defers some steps to subclasses.Home Builders use the template method when developing a new subdivision.A typical subdivision consits of a limited number of floor plans with diff variations available for each.Within a floor plan, the foundation, framing, plumbing, and wiring will be identical for each house. Variation is introduced in the later stages of construction to produce a wider variety of models. [Michael Duell, “Non-software examples of software design patterns”, Object Magazine, Jul 97, p54]

Template method pattern could be refactored using an interface that explicitly signals the methods requested to subclasses and also the state needed by them from the abstract class.

Rules of Thumb:
Strategy is like Template Method except in its granularity.[Coplien, C++ Report, Mar 96, p88]
Template method uses inheritance to vary part of an aligorithm.Strategy uses delegation to vary the entire aligorithm. [GOF, p330]

Also Alex has a good explanation of why he hates Template Pattern.Even i do agree to some extent.

Below example gives an implementation of Template Design Pattern.

package patterns;

abstract class TitleInfo {
 private String titleName;

 // The Template Method.
 // Calls the concrete class methods,is not overridden

 public final String processTitleInfo() {
  StringBuffer titleInfo=new StringBuffer();
  return titleInfo.toString();

 public final void setTitleName(String titleNameIn) {

 public final String getTitleName() {
  return this.titleName;

 public abstract String getTitleBlurb();

 public String getDvdEncodingRegionInfo() {
  return " ";


class DvdTitleInfo extends TitleInfo {
 String star;
 char encodingRegion;

 public DvdTitleInfo(String titleName,String star,char encodingRegion) {

 public char getEncodingRegion() {
  return encodingRegion;

 public void setEncodingRegion(char encodingRegion) {
  this.encodingRegion = encodingRegion;

 public String getStar() {
  return star;

 public void setStar(String star) {
  this.star = star;

 public String getTitleBlurb() {
  return ("DVD: " + this.getTitleName() + ", starring " + this.getStar());

 public String getDvdEncodingRegionInfo() {
        return (", encoding region: " + this.getEncodingRegion());

class BookTitleInfo extends TitleInfo {
 private String author;

 public BookTitleInfo(String titleName,String author) {

 public String getAuthor() {
  return author;

 public void setAuthor(String author) {
  this.author = author;

 public String getTitleBlurb() {
  return ("Book: " + this.getTitleName() + ", Author: " + this.getAuthor());

public class TemplatePatternDemo {

 public static void main(String[] args) {
  TitleInfo bladeRunner=new DvdTitleInfo("Blade Runner","Harrison Ford",'1');
  TitleInfo electricSheep=new BookTitleInfo("Do Androids Dream of Electric Sheep?","Philip");

  System.out.println(" ");
  System.out.println("Testing bladeRunner" + bladeRunner.processTitleInfo());
  System.out.println("Testing electricSheep" + electricSheep.processTitleInfo());

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Share This

Share this post with your friends!