Home > Design Patterns, dotnet 4, SOLID > Template Method Pattern

Template Method Pattern

In my 16 years of software development I have to say that "Template Method Pattern" is one of the most understated but heavily used pattern, we all have used it in some form or the other but never realized that it is a pattern.In the design pattern world it is define as

  The Template Method patterns defines the skeleton of an algorithm in a   method,deferring some steps to subclasses.

It basically means that the template method will define a series of steps which is a well document process for that domain, however each steps can behave in different ways depending on rules or conditions.Hmmm… sounds very complicated no it’s not.

First lets have a look how the UML class diagram of template method pattern looks

 

Template pattern - UML Diagram

As usual I will start with a simple example and I’ll try my best to be more real world. Lets say you are looking at writing a document processing kind of functionality for an enterprise and this is how the user defines the process..

  Based on different types and the use of the document we have different template,   once the template is applied we just change few names, address etc on the   document, format the document and send it .

Does look like Mail merge sort of stuff and this is how we start working it out in the OOP world.

Document process template 

1) Start up or Initialization.

2) Load meta data.

3) Apply template based on the meta data.

4) Format the document and do some spell check or pagination etc.

5) Finalize the document which could mean send the document.

Wow that’s a lot of methods but that’s what a process in a system would be and you can easily say then when ever you have workflow kind of process with some slight differences of one or two methods then there is a good potential for the template method pattern.

Lets model this in a class diagram with the template method pattern.

 

Document Processor Template model

Hmmm .. so what happened there this looks pretty much what the Template method pattern UML diagram looks and still it’s not that clear. First thing you must be wondering that in the DocumentProcessTemplate all the methods are italics except the Process Document. It simply means that ProcessDocument method is a concrete method and rest of them are abstract and lets write some code for abstract DocumentProcessTemplate class.

Document Process Template

 

public abstract class DocumentProcessTemplate
{
    public DocumentType DocumentTypeTemplate { get; set; }
    public MetaDataType MetaDataTypeTemplate { get; set; }

    public abstract void Startup();
    public abstract void LoadMetadata();
    public abstract void LoadTemplate();
    public abstract void ApplyTemplate();
    public abstract void FormatDocument();
    public abstract void FinalizeDocument();

    public void ProcessDocument(DocumentType documentType,
                                MetaDataType metaDataType)
    {
        DocumentTypeTemplate = documentType;
        MetaDataTypeTemplate = metaDataType;

        Startup();
        LoadMetadata();
        LoadTemplate();
        ApplyTemplate();
        FormatDocument();
        FinalizeDocument();
    }
}

 

Aha so this is what the template method looks like, it is nothing more like a contract.The ProcessDocument method is saying that this is the sequence of steps it takes to process any type of document and the class which implements it can implement it’s own action(methods), but the base class will enforce the sequence of execution.

And lets have a look how these two different time of DocumentProcessor looks like

Letter Processor

public class LetterProcessor : DocumentProcessTemplate
{
    public override void Startup()
    {
        //may be don’t need anything
    }

    public override void LoadMetadata()
    {
        switch (MetaDataTypeTemplate)
        {
            case MetaDataType.Personal:
                // May be we need to do more
                //complex work here..
                break;
            case MetaDataType.Organizational:
                break;
        }
    }

    public override void LoadTemplate()
    {
        switch (DocumentTypeTemplate)
        {
            case DocumentType.Email:
                //Apply email settings
                break;
            case DocumentType.Memo:
                //Apply Memo settings
                break;
        }
    }

    public override void ApplyTemplate()
    {
        // Can be any combination based on meta data return
    }

    public override void FormatDocument()
    {
        //may be we need different formatting
        //based on document type like
        // SpellChecker();
        // Translator(); etc functionality
    }

    public override void FinalizeDocument()
    {
        // Final process which could be
        // for email directly send to
        // the client but for Memo
        // print it out and send an email to
        // the company postal department to
        //dispatch the document.
    }

 
}

Agreement Processor

public class AgreemantProcessor : DocumentProcessTemplate
{
    public override void Startup()
    {
        //Since it’s an agreement may
        //be we need to process some
        // pre requisite documents
    }

    public override void LoadMetadata()
    {
        //Some decision making
    }

    public override void LoadTemplate()
    {
        switch (DocumentTypeTemplate)
        {
            case DocumentType.Letter:
                // some special logic
                break;
            case DocumentType.Memo:
                // some special logic
                break;
        }
    }

    public override void ApplyTemplate()
    {
       
    }

    public override void FormatDocument()
    {
       
    }

    public override void FinalizeDocument()
    {
        //Send to the business review
        //team for a thorough review
    }
}

As you can see how these two document processor class differ in their own implementation. A letter process algorithm based on whether it’s Personal or Organizational will have a different implmentation than a Agreement Processor but it’s the base class which controls(enforces) the execution flow. With this pattern we are still sticking to the good design principles of OOP ( inheritance and polymorphism) and we are also using the Single Responsibility principle, as the single responsibility of the abstract DocumentProcessTemplate is to control the flow of the processing.

This pattern is also useful when there is a lot of cluttering of code with lot of decision making code like if elseif else or two many switch statement or complex calculation(“complex business rules”).

This is just a tip of an iceberg and it’s a very useful,simple yet powerful pattern to use.Rest is upto your imagination and refactoring :).

  1. Dom
    December 19, 2010 at 10:53 pm

    Fantastic article on template pattern – best I have seen so far – have a great christmas break champ!!!
    Cheers
    Dom

    • December 21, 2010 at 12:52 am

      Dom :

      Fantastic article on template pattern – best I have seen so far – have a great christmas break champ!!!
      Cheers
      Dom

      Hi Dom,
      Thanks mate and your words of encouragement will motivate for some better stuff in the future. You have lovely christmas and a happy new year, I am in fact flying on christmas day to India and coming back on Jan 12th.

      Cheers,
      Prashant Brall

  2. Yogo
    January 11, 2011 at 10:04 pm

    Nice work partner. Back from India yet?

    • January 14, 2011 at 3:07 am

      Hi Yogesh,
      Thanks, yep just got back from India .

  1. January 27, 2011 at 5:13 am
  2. January 20, 2012 at 11:18 pm

Leave a comment