Where should we use Template Method - pattern?

0 votes
asked Oct 12, 2009 by anonymous

Can anyone let me know some example situations where Template Method - pattern should be used?

Give me some real-world use from your own experience.

(I have so far found it useful only for mapping data in the DA layer. Sorry!!!)

7 Answers

0 votes
answered Jan 12, 2009 by burt

I have used the template method for Business Logic where a number of components shared the same process but the implementation was slightly different.

0 votes
answered Oct 12, 2009 by pascal-thivent

A Template method pattern provides a skeleton for performing any sort of algorithm or an operation, and it allows the sub-classes to re-define part of the logic.

Pros: Natural fit for building frameworks, so that parent framework classes can make callbacks into methods implemented in child.

Examples:

  • java.util.AbstractList
  • Servlet's doGet and doPost methods
  • MDB's onMessage method
  • Struts Action class
  • Spring's data access classes

Cons: Restricts you to a single inheritance in Java.

0 votes
answered Oct 13, 2011 by thurein

The most important thing in template method is that you have to define a series of abstract methods as steps or an algorithm and let the sub class substitute with the concrete implementation for those methods.

I applied in one of the document generation program.

public abstract DocumentGenerator() 
{
   generateHeader();
   generateBody();
   generateDetails();
}
public HTMLDocGenerator : DocumentGenerator()
{
   public override generateBody()
   {
     //generate as in html format
   }
}

You can have different implementation like PDF generator csv generator and the value here is they comform to the algorithm (generate -> header, body, details).

0 votes
answered Jan 12, 2014 by sai-sunder

A template pattern should be used when there is an algorithm with many implementations. The algorithm is defined in a function in base class and implementation is done by the base class and subclasses. A detailed explanation with a real-time example is given in http://preciselyconcise.com/design_patterns/templatemethod.php

0 votes
answered Jan 30, 2015 by jxramos

I'll sketch one real world example where I utilized some template methods.

In a C++ computer vision algorithm application the behavior of the algorithm was designed to assume a couple of flavors of algorithm behavior based upon some options read at run time according to an enum tucked into a config file loaded at startup. The overall skeleton of the algorithm was identical except for some key callbacks stuffed in the middle of what would otherwise be an identical section of code that would be brutally duplicated just to call different functions at that level. These callbacks I wanted to use were abstracted into the template method base class and the template method pattern prevented all that code duplication. The enum we used basically dictated what subclass I instantiated my base class pointer to point to and thus lend the algorithm its associated bit of flavor in behavior.

Now some of the motivations behind this variety of flavors of the running algorithm was an online vs offline functionality of software that controlled our instrument. The offline flavor pulled with it richer debug/diagnostic output and kept a coordinate system local to some image pixels while the online flavor kept things in an absolute coordinate space and maintained concerns specific to the running instrument with all its robotics and what not. Another enum drove a selection among a set of classifiers we used for some machine learning as well since different classifiers were trained under different sets of data that otherwise flowed identically through the body of code but needed to be interpreted differently based on some governing conditions for how that data was created.

I believe this sort of use case I had arose from what has been called the hole in the middle problem.

0 votes
answered Sep 15, 2017 by gorkemhalulu

The Template method defines the skeleton structure of an algorithm but defers certain steps and details to subclasses. The structure and the flow of the algorithm remain static, but the details of the steps are deferred to subclasses.

I used Template Method Pattern to prepare document content. There were many different kinds of document that each type has its own small modifications. However, the main process of document preparation was same for all.

0 votes
answered Sep 15, 2017 by mmkarami

I tried to give you some real-world examples, and some common situations where Template Method pattern should be used.

  • When you want your program be "Open For Extension” and also “Closed for Modification”. This means that the behavior of the module can be extended, such that we can make the module behave in new and different ways as the requirements of the application change, or to meet the needs of new applications. However, The source code of such a module is inviolate. No one is allowed to make source code changes to it. In following example, you can add new manner of salary calculation (such as Remotely class) without changing the previous codes.

    public abstract class Salary {

    public final void calculate() {
        System.out.println("First shared tasks is done.");
        getBaseSalary();
        System.out.println("Second shared tasks is done.");
    }
    
    public abstract void getBaseSalary();
    

    }

    public class Hourly extends Salary {

    @Override
    public void getBaseSalary() {
        System.out.println("Special Task is done.");
    }
    

    }

    public class Test {

    public static void main(String[] args) {
        Salary salary = ....
        salary.calculate();
    }
    

    }

  • When you face many same line of codes that are duplicated through deferring just some steps of your algorithm. When you are implementing content of a method or function you can find some section of your code that vary from one type to another type. The feature of this sections are that one can redefine or modify these sections of an method or function without changing the algorithm's (method or function) main structure. For example if you want to solve this problem without this pattern you will face this sample:

function0: function1: ... functionN:

1       1               1
2       2               2
...     ...             ...
5       6               n
3       3               3
4       4               4
...     ...             ...

As you can see, section cods 5, 6, n are different vary from one function to another function, however you have shared sections such as 1,2,3,4 that are duplicated. Lets consider a solution with one of famous java libraries.

public abstract class InputStream implements Closeable {

    public abstract int read() throws IOException;

    public int read(byte b[], int off, int len) throws IOException {
        ....

        int c = read();
        ....
    }

    ....

}

public class ByteArrayInputStream extends InputStream {  

    ...

    public synchronized int read() {
        return (pos < count) ? (buf[pos++] & 0xff) : -1;
        }
    ...
}
  • When you as a designer of a framework, want that your clients just to use any executable code that is passed as an argument to your framework, which is expected to call back (execute) that argument at a given time. This execution may be immediate as in a synchronous callback, or it might happen at a later time as in an asynchronous callback. Lets consider one of famous ones.

    public abstract class HttpServlet extends GenericServlet implements java.io.Serializable { protected void doGet(HttpServletRequest req, HttpServletResponse resp) { ... }

    protected void service(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
            ....
            doGet(req, resp);
            ...
        }
        ...
    }
    

    }

    public class MyServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    
            //do something
        ...
    }
    ...
    

    }

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...