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.

Managing the daily itinerary of company employees can be a time-consuming task. It would be much easier if the daily tasks can be programmed to occur automatically using a program. Mark has been working for Yahaa Inc for the past four years; he is a programmer, and his daily routine is exclusive doing programming-related tasks. Elisa is a marketer for the same company; like Mark, she has her daily routine set, and hers is exclusive doing marketing tasks.

As a programmer, Mark's daily routine in the company looks like this:

  • When Mark the programmer enters the company, the first thing he has to do is to mark his attendance in the attendance tracking system; this makes sure that he will be paid for the day (markAttendance()).
  • After that, he then proceeds to do his job according to his role (doingProgrammingTask()).
  • Finally, he writes a detailed daily report about what he has completed for the day (reportDailyCompletion()).

Now Elisa the marketer has almost the same routine as Mark except for step two. As a marketer, the second part of routine is to do marketing-related tasks.

We can easily spot the code duplication in those two classes above. Both programmer and marketer share some common procedures.

How can we make the code better?

We can obviously make it better if we can define some common procedures in the super class but still give flexibility to the subclasses to define its own function. This is the time to apply the Template Method Pattern.

It is time to rework our code. Let's define an abstract class with some predefined functions:

This class looks very similar to either Programmer or Marketer class, except we have removed the function that varies between the two classes and replace it with an abstract class doWork().

Now let us rework both Programmer and Marketer classes:

As we can see, both Programmer and Marketer classes have become much cleaner and there is no more code duplication.

In our example, we define the skeleton of an algorithm in a method (workRoutine() method in Employee class), deferring some steps (doWork()) to subclasses (Programmer and Marketer classes). Template method (doWork() method in Employee class) let subclasses (Programer and Marketer class) redefine certain steps (doWork()) of an algorithm without changing the algorithm's structure.

The end

Hopefully this simple tutorial helped you with your development.
If you like our post, please follow us on Twitter and help spread the word. We need your support to continue.
If you have questions or find our mistakes in above tutorial, do leave a comment below to let us know.