11

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!!!)

Dave Schweisguth
  • 36,475
  • 10
  • 98
  • 121
user366312
  • 16,949
  • 65
  • 235
  • 452

9 Answers9

11

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.

Pascal Thivent
  • 562,542
  • 136
  • 1,062
  • 1,124
  • 2
    I just had a look at the AbstractList and HttpServlet classes. I don't see any "template methods" in them. I suspect you are confusing the Template Method pattern with simple "inversion of control" uses. The pattern is not about having a base class whose methods are called by a framework, but about having a method which encapsulates a algorithm which can be customized by subclasses that override special extension points (overridable methods of the base class called from the template method, which itself is not meant to be overridden). – Rogério Feb 14 '10 at 16:00
  • @Rogerio The fact that *you* don't see the pattern doesn't mean that `HttpServlet` and `AbstractList` are not good examples. With `HttpServelt`, subclasses **do** implement `doGet`, `doPost`, etc which are the extensions points called in `service` (which is the only method called by the container for each request as per spec). With `AbstractList`, subclasses **do** implement `get`, `size`, `set`, `remove` (just look at the javadoc header) which are the extension points. I don't see any IoC for the mentioned extension points. – Pascal Thivent Feb 14 '10 at 21:07
  • @Rogerio So, instead of teaching me what Ioc and the the template pattern are, maybe learn to recognize them first (use Google if you think I'm wrong before to claim *your* truth). Also maybe learn how servlet work. But don't blame me for *your* ignorance. Consequently, I do not thank you for your irrelevant downvote that I ask you to reconsider. – Pascal Thivent Feb 14 '10 at 21:10
  • Yes, the HttpServlet#service method is very much like a Template Method, except that is not meant to be called from application code, but only from the web container; so it could be taken as an example, though not a very good one. Now, doGet and doPost certainly aren't examples of Template Methods at all; rather, they are examples of the "primitive operations" called from the template method. This is all described in the GoF book, of course (pages 325-330). – Rogério Feb 14 '10 at 22:58
  • In the case of AbstractList, the "get" method (abstract in this class) is only called from non-public inner classes, and "size" (with a trivial implementation which is never overriden, at least in other JDK classes) is not called at all from inside AbstractList. So, they definitely are not Template Methods, nor "primitive operations" called from some Template Method. There is no way to deny this, it's a fact any Java programmer can verify for himself. – Rogério Feb 14 '10 at 23:00
  • 1
    Inversion of control (also known as the "Hollywood principle" - see http://en.wikipedia.org/wiki/Inversion_of_control) is used in the Servlet API and in the Struts framework, where the client programmer implements methods which are called by the framework (the web container, in the case of Servlets), as opposed to calling framework methods from client code (which is the regular case where you simply use a class library, without the inversion which characterizes a "framework"). I suspect you may be confusing it with "dependency inversion", which is a whole different matter. – Rogério Feb 14 '10 at 23:08
  • 2
    You say "subclasses do implement get, size, set, remove": true, since AbstractList is only a partial implementation - except for the `size` method which is fully implemented in AbstractList itself. Clearly, you must understand that a Template Method is implemented in the base class and not overriden in a subclass; only the "primitive operations" called from the template method are implemented in the subclass. For example, the `AbstractList#get(int)` method is abstract and therefore could only be a "primitive operation" (which you agree, right?). But there is no template method in this class. – Rogério Feb 14 '10 at 23:19
  • @Rogerio Ok, wrong examples, the right one is `addAll(int index, Collection extends E> c)`. Regarding `HttpServlet`, I still think this is a valid example too. But I won't argue more with you. If you have another point of view, just write your own answer. – Pascal Thivent Feb 14 '10 at 23:47
  • You're right, `addAll` qualifies as a Template Method, which relies on a subclass implementing the `add(int, E)` "primitive operation" method. Maybe not so good an example because it only uses one primitive operation, but it's valid. – Rogério Feb 15 '10 at 11:51
  • @Rogerio I'd prefer to forget all this (including the comments). I got carried away and said something I didn't mean yesterday. I guess I was in a bad day and apologize for that. – Pascal Thivent Feb 15 '10 at 12:52
  • That's ok, Pascal. I did realize at the time that it was just an over-reaction. – Rogério Feb 15 '10 at 13:38
  • One more example: grid view & dialog view classes in abstract layer of UI systems – Nikolay Shabak Aug 02 '16 at 19:48
6

An application of the Template Method pattern has two main characteristics:

  1. There is a base class (in Java, one only with protected constructors and optionally declared as abstract) which will be subclassed in client code.
  2. There are two groups of methods defined in the base class: a) one or more template methods (typically only one) and one or more primitive operation methods (typically more than one). Each template method represents a high level operation, implemented in the base class itself in terms of the primitive operations, which are meant to be implemented/overriden in each specific subclass. Normally, the template method is public and non-overridable (final, in Java); its API documentation must specify precisely which primitive operation methods it calls, and when (that is, it must describe the "algorithm"). A primitive operation method, which represents a step in the algorithm, should be non-public but overridable (protected, in Java), and can be of two types: a) an abstract method which must be implemented in the subclass; b) a method with a default/empty implementation which may be overriden in the subclass.

One good example in the Java 6 SDK is the execute() method of the javax.swing.SwingWorker class (it is a public final void method). In this case, the primitive operation methods are doInBackground(), process(List), and done(). The first one is abstract and therefore requires an implementation in the subclass; it's called by the template method in a background thread. The other two have empty implementations and can optionally be overriden in the subclass; they are called during and at the end of processing, respectively, in the EDT (the Swing Event Dispatch Thread), to allow updates to the UI.

In my own experience, I have sometimes used this pattern. One such case was a Java base class implementing the java.util.Iterator interface, where next() was the template method and there was only one primitive operation method responsible for instantiating a specific domain entity class (this was meant to be used when iterating over a list of persistent domain entity objects, using JDBC). A better example in that same application was a base class where the template method implemented a multi-step algorithm intended to populate a "business entity maintenance screen" (using Swing) from a given list of persistent entities; primitive operations methods were called to 1) clear the current screen state, and 2) add an entity in a table view inside the screen; optionally, other primitive operations were called from the template method if the screen was editable.

In the end, I must say that although this certainly is a useful design pattern, not so often a situation comes up where it really is applicable. Simply having a base class with methods that get overriden in a subclass (a much more common situation, in my experience) is not enough, by itself, to qualify as an application of the pattern.

Rogério
  • 16,171
  • 2
  • 50
  • 63
4

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
            ...
        }
        ...
    }
    
Abhishekkumar
  • 1,102
  • 8
  • 24
MMKarami
  • 1,144
  • 11
  • 14
3

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).

Thurein
  • 6,645
  • 5
  • 22
  • 23
2

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

Sai Sunder
  • 1,001
  • 1
  • 11
  • 16
  • 2
    >> "A template pattern should be used when there is an algorithm with many implementations." Nope, that's a mistake. What you described is the *Strategy* pattern. The Template Method pattern is about letting subclasses replace certain steps in an algorithm. – Karoly Nyisztor Nov 26 '17 at 16:53
2

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.

jxramos
  • 7,356
  • 6
  • 57
  • 105
1

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

Burt
  • 7,680
  • 18
  • 71
  • 127
1

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.

GorkemHalulu
  • 2,925
  • 1
  • 27
  • 25
0

This article talks about 6 common uses of Template pattern.In the era of ADO.NET i had used template pattern a lot as we had fixed sequence like open , executequery and close connection , but the executequery would have queries different as per different table structure.

https://www.codeproject.com/Articles/307452/common-use-of-Template-Design-pattern-Design-pat

Above articles talks about six common uses of template pattern :-

  1. Flexible extendable generalized specialized user interfaces
  2. ASP.NET page life cycle
  3. Code generators
  4. XML parser
  5. Validation in business components
  6. Customizable logging utility
Shivprasad Koirala
  • 27,644
  • 7
  • 84
  • 73