Template Method Design Pattern

Please check out my new video on the Template Method Design Pattern:

This post complements the video tutorial by adding the source code used in the video and also provides some additional information.

As per Wikipedia, the template method pattern is a behavioral design pattern that defines the program skeleton of an algorithm in an operation, deferring some steps to subclasses. It lets one redefine certain steps of an algorithm without changing the algorithm’s structure.

Let me explain the Template Design Pattern first and then we will revisit the definition. Lets assume that we are implementing an algorithm that has three steps that are executed sequentially. There is a “main” method invokes the three sub steps in the right sequence. The “main” method is called the template method and is what is invoked to execute the algorithm. The idea here is that we cannot change sequence of the three steps but what happens in these steps can be overridden or implemented differently by different classes. So the main/template method and the three methods that implement the three sub steps can be defined in a class. The three steps can be overridden in a sub class but the algorithm would still be executed from the parent class’s template method. The parent class can be declared as abstract that will force the consumers of this algorithm to always use a subclass. But the template method will be available by inheritance to each sub class.

In our prototype, the algorithm is the sequence of steps to register a student. The three steps are:
1. VerifyPrerequisites (check if the student meets the required pre-requisites for a course)
2. ProcessPayment (process course fee if the student meets prerequisites)
3. SendNotification (Send a notification to the student to confirm their registration if payment is processed successfully)

The main/template method is defined as RegisterStudent and it invokes steps 1-3 in the correct order. Lets take a look at the parent class. In our case, steps 1 and 3 have to be overridden by a sub class. But step 2 is implemented in the parent class because the ProcessPayment step is expected to to be common to all sub classes of CourseRegistrationHelper.

 public abstract class CourseRegistrationHelper
    {
        //template method
        public void RegisterStudent()
        {
            VerifyPrerequisites(); //step 1
            ProcessPayment(); //step 2
            SendNotification(); //step 3
        }
 
        //must be overridden by sub classes
        //this is step 1
        protected abstract void VerifyPrerequisites();
        //default implementation of this step is provided
        //this is step 2
        protected void ProcessPayment()
        {
            Console.WriteLine("Processing Payment the generic way");
        }
 
        //must be overridden by sub classes
        //this is step 3
        protected abstract void SendNotification();
    }

Two universities implement this abstract class in two different ways. The implementation is methods in the entire prototype is trivial but the idea here is to understand the structure of the Template Method Design Pattern.

This is the way University A implements this.

public class UniversityACourseRegistrationHelper : CourseRegistrationHelper
    {
        //step 1
        protected override void VerifyPrerequisites()
        {
            Console.WriteLine("Validate transcript");
        }
 
        //step 3
        protected override void SendNotification()
        {
            Console.WriteLine("Send a letter");
        }
    }

This is the way University B implements this:

 public class UniversityBCourseRegistrationHelper : CourseRegistrationHelper
    {
        //step 1
        protected override void VerifyPrerequisites()
        {
            Console.WriteLine("Validate university records");
        }
 
        //step 3
        protected override void SendNotification()
        {
            Console.WriteLine("Send email");
        }
    }

Now we can invoke the two algorithms in a c# console application.

class Program
    {
        static void Main(string[] args)
        {
            var HelperA = new UniversityACourseRegistrationHelper();
            //invoke template method
            HelperA.RegisterStudent();
 
            var HelperB = new UniversityBCourseRegistrationHelper();
            //invoke template method
            HelperB.RegisterStudent();
 
            Console.WriteLine("Press any key to close this window...");
            //wait for user to input a key
            Console.ReadKey();
        }
    }

The output looks like this:

Validate transcript Processing Payment the generic way Send a letter Validate university records Processing Payment the generic way Send email Press any key to close this window...

The template method RegisterStudent is available to both UniversityACourseRegistrationHelper and UniversityBCourseRegistrationHelper by inheritance but steps 1 and 3 are overridden by each class. But when RegisterStudent is invoked on either class, step 2 (ProcessPayment) is executed because its implemented in the parent class. This makes it flexible for us to implement a step in the algorithm either in the parent class or in the derived class. Can we have the flexibility to provide a ‘default’ implementation of a step in the parent class and override the step in a sub class if necessary? Yes, absolutely.

Lets tweak the parent class slightly and make the ProcessPayment method virtual (overridable in a sub class).

 protected virtual void ProcessPayment()

Now lets override this method implementation in the UniversityACourseRegistrationHelper like this:

    public class UniversityACourseRegistrationHelper : CourseRegistrationHelper
    {
        //step 1
        protected override void VerifyPrerequisites()
        {
            Console.WriteLine("Validate transcript");
        }
 
        //step 2
        protected override void ProcessPayment()
        {
            Console.WriteLine("Processing payment University A way");
        }
 
 
        //step 3
        protected override void SendNotification()
        {
 
            Console.WriteLine("Send a letter");
        }
    }

Now the output of this program will look like this:

Please note that UniversityBCourseRegistrationHelper is still using the default implementation of ProcessPayment. But all sub classes have the flexibility of either using the default implementation in the parent class or provide it’s own implementation.

Those steps that are different for each concrete implementation in a sub class must be declared as abstract so each subclass will have to provide an implementation.

Lets revisit the Wikipedia definition. The ‘program skeleton’ on the Wikipedia page is defined in the RegisterStudent template method and that cannot be changed. But the individual steps are deferred to a subclass (like UniversityACourseRegistrationHelper). The individual steps in our case are VerifyPrerequisites, ProcessPayment and SendNotification.

The Wikipedia link has an excellent example in multiple programming languages and can be viewed here.

Hope you liked this post and the video. Your feedback is valuable to me. Also, i’d like to hear your experience with the Template Method Design Pattern.