Skip to main content

Template Method Design Pattern In Java

Greetings!

Template Method pattern is a behavioral pattern.
We put our businesss logic in abstract in a super class and let the sub classes override specific steps without changing the original structure.

Source code for this post can be found in my github account. [source-code]

When we have a common steps to do something but some steps vary, we can do it using bunch of if else statements. But the problem is things are tightly coupled and when new things need to be added we have to change our class. This leads our class difficult to main. For these kind of problems Template Method can be used.

Definition of Gof;
"Defines the skeleton of an algorithm in a method, deferring some steps to sub-classes. Template Method lets sub-classes redefine certain steps of an algorithm without changing the algorithm's structure."


"Don't call us, we'll call you. - allow low-level components to hook themselves into a system, but the high-level components determine when they are need and how."

Template method has easy two steps.
  • Define algorithm steps in super class.
  • Implement specific steps in sub class.

Working Example

Let's say we want to generate document Pdf, Excell, etc. Each file can have different ways to generate the document but loading data from the database, convert document into stream, etc are commmon operations. But steps are same. We add those common steps into super class and let the sub class define the what varies.

We can start by creating super class. In our case it is DocumentTemplate. Note that template method is final.

package com.slmanju.patterns;

public abstract class DocumentTemplate {

    public final void getDocument() {
        System.out.println("Load information...");

        generate();

        System.out.println("Finalize document creation...");
    }

    protected abstract void generate();

}


Now we can extend it to create our concrete implementation.

package com.slmanju.patterns;

public class PdfDocumentTemplate extends DocumentTemplate {

    @Override
    protected void generate() {
        System.out.println("Generating pdf document.");
    }

}


Let's run our application.

package com.slmanju.patterns;

public class App {

    public static void main(String[] args) {
        DocumentTemplate documentTemplate = new PdfDocumentTemplate();
        documentTemplate.getDocument();

        System.out.println("----------");

        documentTemplate = new ExcelDocumentTemplate();
        documentTemplate.getDocument();
    }

}


Things to note;

  • Algorithm steps are fixed but some implementations may vary. Subclasses are responsible to override necessary steps.
  • Subclass doesn't call super class. Instead it is super class which controls the flow. This is called 'Hollywoord principle'.
  • What if a step is based on a condition? We can add if condition with a method which may implement by sub classes. This is called a Hook. Super class may provide the default condition.
  • Template method and Factory method patterns are look similar. But the intent is different. Factory method is for creating objects. Template method is to define behaviour.
  • Strategy pattern uses composition while Template method uses inheritance.

Happy coding :)

Comments