I've been a zone leader with DZone since 2008, and I'm crazy about community. Every day I get to work with the best that JavaScript, HTML5, Android and iOS has to offer, creating apps that truly make at difference, as principal front-end architect at Avego. James is a DZone Zone Leader and has posted 639 posts at DZone. You can read more from them at their website. View Full User Profile

Design Patterns Uncovered: The Template Method Pattern

  • submit to reddit

Today's pattern is the Template Method pattern, which defines a stub for an algorithm, deferring some implementation steps to subclasses.

Template in the Real World 

The Template Method pattern is used when two or more implementations of a similar algorithm exist. In the real world templates are used all the time: for architectural plans, and throughout the engineering domain. A template plan may be defined which is then built on with further variations. For example, a basic house plan can have many variations such as adding an extensions or using a different heating system.

Design Patterns Refcard
For a great overview of the most popular design patterns, DZone's Design Patterns Refcard is the best place to start. 

The Template Pattern

The Template Method pattern is known as a behavioural pattern, as it's used to manage algorithms, relationships and responsibilities between objects. The definition of Template Method provided in the original Gang of Four book on Design Patterns states: 

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 algorithms structure.

In practice, the Template Method pattern is quite simple - let's look at a class diagram representation

The AbstractClass contains the templateMethod(), which should be made final so that it cannot be overridden. This template method makes use of other operations available in order to run the algorithm, but is decoupled for the actual implementation of these methods. All operations used by this template method are made abstract, so their implementation is deferred to subclasses.

The ConcreteClass implements all the operations required by the templateMethod that were defined as abstract in the parent class. There can be many different ConcreteClasses. 

The Template Method pattern makes use of the Hollywood Principle: Don't call us, we'll call you. The template method in the parent class controls the overall process, "calling" subclass methods when necessary. The Hollywood principle avoids low level components depending on high level components, and instead give these low level classes (ConcreteClass) a way of hooking into the parent class (AbstractClass). 

When broken down, there are four different types of methods used in the parent class: 

  • Concrete methods
    Standard complete methods that are useful to the subclasses. These methods are usually utiity methods.
  • Abstract methods
    Methods containing no implementation that must be implemented in subclasses.
  • Hook methods
    Methods containing a default implementation that may be overidden in some classes. Hook methods are intended to be overridden, concrete methods are not.
  • Template methods
    A method that calls any of the methods listed above in order to describe the algorithm without needing to implement the details.

When Would I Use This Pattern?

The Template Method pattern is used when 

  • When behaviour of an algorithm can vary, you let subclasses implement the behaviour through overriding
  • You want to avoid code duplication, implementing variations of the algorithm in subclasses
  • You want to control the point that subclassing is allowed.

Template Method may not be an obvious choice in the beginning, but the usual sign that you should use the pattern is when you find that you have two almost identical classes working on some logic. At that stage, you should consider the power of the template method pattern to clean up your code.

As you can imagine, use of the Template Method is fairly common. You'll find it used in the Arrays class uses it for sorting. JFrame uses update() as a template method, subclasses of the JFrame use paint(Graphics g) as their hook method.

So How Does It Work In Java?

For our Java example, we'll use a cross compiler as an example. First, we'll create a generic cross compiler base class, with it's crossCompile() method being the glue for the whole algorithm to run.

public abstract class CrossCompiler 

public final void crossCompile()

//Template methods
protected abstract void collectSource();

protected abstract void compileToTarget();

Next we'll create two specific implementations of our cross compiler, for iPhone and for Android: 


public class IPhoneCompiler extends CrossCompiler
protected void collectSource()
//anything specific to this class

protected void compileToTarget()
//iphone specific compilation

public class AndroidCompiler extends CrossCompiler
protected void collectSource()
//anything specific to this class

protected void compileToTarget()
//android specific compilation


To complete this example, here is how you would use your cross compilers

public class Client
public static void main(String[] args)
CrossCompiler iphone = new IPhoneCompiler();

CrossCompiler android = new AndroidCompiler();


Watch Out for the Downsides

There are some downsides to the template method pattern. Firstly, your base classes tend to get cluttered up with a lot of seemingly unrelated code. Program flow is a little more difficult to follow - without the help of stepping through the code with a debugger. Alex Miller provides a detailed rundown of the reasons he hates the template method pattern in his blog. 


Other Articles in This Series
The Observer Pattern
The Adapter Pattern
The Facade Pattern
The Factory Method Pattern
The Abstract Factory Pattern
The Singleton Pattern
The Strategy Pattern
The Visitor Pattern

The Decorator Pattern
The Proxy Pattern
The Command Pattern
The Chain of Responsibility Pattern

Next Up

We're going to look at the Prototype pattern later this week.



Dapeng Liu replied on Tue, 2010/04/06 - 5:30am

Another use case for Template, which is also my fav, is DB transaction template
before entering the subclass codes, get the connection, start a transaction
run the subclass' code
commit the transaction
on exception, rollback back the transaction
finally resource clean up

Hieu Lam replied on Tue, 2010/04/06 - 10:29am

Maybe there's a copy-paste error with the pattern definition.

James Sugrue replied on Tue, 2010/04/06 - 10:59am in response to: Hieu Lam

Thanks for spotting that - had the wrong definition in there.. All fixed now :)

Mohamed El-beltagy replied on Wed, 2010/04/07 - 5:13am

I have used this pattern extensivly many times before and found it very useful.

For example, I made a framework based on Struts 1.x, a BaseAction class as the template and all of our actions extending it. The BaseAction has the execute method as the concerete method doing lots of things that are framework specific (the framework that istied to business and not related to Struts), and we had some mix of abstract and hook method that are used to do the buisness and decide the flow in some cases.

It was really useful for implementation and faster.

In regards to the downsides, you got to the point when you said:

Program flow is a little more difficult to follow - without the help of stepping through the code with a debugger.

 Of course, we are talking about the need to debug a certain problem. Although if you thought about it, the business is really in the concerete classes, so once the template class is implemented, tested and is final, you only need to debug and trace the implementing classes.


James Sugrue replied on Thu, 2010/04/08 - 2:30am in response to: Mohamed El-beltagy

Thanks for the comments. You're right, once you know where to look, and provided you don't have too many concrete classes, it's not so bad for debugging. One thing that is true for all pattern implementations is that once you understand the pattern well, and know where it is used in your code, debugging becomes easier. Without a real understanding, the debug process can be frustrating

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.