Home > Design Patterns > Template Pattern

Template Pattern

April 29th, 2008

In this article I want to discuss the Template Pattern. One of the main reasons why I wanted to talk about it is that it holds a few similarities to the Strategy Pattern (which I recently wrote an article on). At the end of this article, I will discuss the differences between the two in hopes to help you choose what fits best for you.

So what is a Template pattern? A Template is a way for use to define the skeleton of an algorithm in an abstract class. The skeleton for our algorithm is defined within a final method, so the outline cannot change. How these methods are carried out are then defined within the subclasses. When used, it gives an inverted control structure, where the super class calls the subclasses methods. This is also how it became known as the Hollywood Method, or “Don’t call us, We’ll call you.”. So lets take a closer look.

In order to keep things in terms of a real world example, lets look at a DAO layer. Normally, there are a few standard steps in a DAO layer.

1.Connect to a database.
2.Retrieve your data.
3.Do something with your results.
4.Close the database connection.

So those are our basic steps of our DAO layer, or better put, its our algorithm. So lets put that into a class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public abstract class AbstractDAO {
	public final void execute(){
		//This is our template method. 
		connectToDB();
		loadData();
		outputResults();
		closeDBConnection();
	}
	//Loading data for each dao will be slightly different. Let the objects define them
	public abstract void loadData();
	//Outputting data for each dao will be slightly different. Let the objects define them
	public abstract void outputResults();
 
	//Opening the database is the same. We can define this here.
	private void connectToDB(){
		System.out.println("\n*****Connecting to database*****");
	}	
 
	private void closeDBConnection(){
		System.out.println("*****Closing database*****\n");
	}
}

So here we have our template class. In our execute method, we have the basic algorithm to retrieve data. Two of the methods will be different across the data access objects(DAO), which is the why methods in which we have defined as abstract (loadData() and outputResults()). The other two will be the same no matter what.

Now lets take a look out the implementations of our DAO’s.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Employees extends AbstractDAO{
 
	@Override
	public void loadData() {
		System.out.println("Loading data for employees");
	}
 
	@Override
	public void outputResults() {
		System.out.println("Outputting results for employees");
	}	
}
 
public class Customers extends AbstractDAO{
	@Override
	public void loadData() {
		System.out.println("Loading data for customers");
	}
 
	@Override
	public void outputResults() {
		System.out.println("Outputting results for customers");
	}
}

Sorry that in this example, I’m using mock data in here. You can put whatever you want in these methods, but its more to just use as an example. Anyways, in each DAO, we only define the loadData and outputResults methods. In a real world example, the loadData method would have a select statement to call the database and the outputResults method would then iterate through the results and do whatever it wants to with them.

Alright, most of this is pretty standard. Lets look at why I got to sound smart and say the template pattern gives us an ‘inverted control structure’. Here is our main class.

1
2
3
4
5
6
7
8
9
public class DAOImpl {
	public static void main(String[] args) {
		Employees employees = new Employees();
		Customers customers= new Customers();
 
		employees.execute();
		customers.execute();
	}
}

Notice that all we are doing is calling the execute method. We are not calling anything directly. We allow our template method (execute) call our functions within our DAOs for us (hence, dont call use, we will call you). Here is our output:

*****Connecting to database*****
Loading data for employee
Outputting results for employee
*****Closing database*****

*****Connecting to database*****
Loading data for customers
Outputting results for customers
*****Closing database*****

Now in a great wondrous world, our algorithm will never have to change. But as we all know, things change and sometimes we need conditional statements within our algorithm. The way we get around this problem is by implementing a “hook”. The hook will allow us to call other methods based on whatever criteria we want. Going back to our, there are often times we want to cache our results. Lets look at how we want to handle that. Going back to our template method. Right after outputResults(), lets add this:

1
2
3
if (doCaching()){
	cacheResults();
}

Then of course, add these to the abstract class as well.

1
2
	public abstract void cacheResults();	
	public abstract boolean doCaching();

For employee, I’ve added this:

1
2
3
4
5
6
7
8
	@Override
	public void cacheResults(){
		System.out.println("Caching results for Employees");
	}
	@Override
	public boolean doCaching(){
		return false;
	}

And for Customers, I’ve added this:

1
2
3
4
5
6
7
8
	@Override
	public void cacheResults(){
		System.out.println("Caching results for customers");
	}
	@Override
	public boolean doCaching(){
		return true;
	}

Now with this, we can conditionally decide when we want to cache our results or not. In this example, we don’t want to cache the employees but we do want to cache the customers. Obviously there would be more to it in a real world example, but you get the gist. So running this, here is what we get.

*****Connecting to database*****
Loading data for Employees
Outputting results for Employees
*****Closing database*****

*****Connecting to database*****
Loading data for customers
Outputting results for customers
Caching results for customers
*****Closing database*****

Done.

Right off the bat, you may notice its somewhat similar to the strategy pattern. In both instances, we are using an abstract methods to decide our things will be carried out. But the main difference is that with a strategy pattern, we are delegating methods to do the work. With strategy, we just assign it an object that is a subclass and use that to carry out the work.

With template methods, we dont worry about assigning delegates at runtime. We have have the basis of our algorithm setup, then we let the objects decide what they want to do in those steps. I suppose you could argue that we are still delegating, but we are delegating the steps of our algorithm TO the subclass. While we can some flexibility with this, we do lose the convenience of swapping at runtime that the strategy pattern gives us.

I have included the source for this for you to look over. I hope that this article has been helpful to you. If you have any questions, feel free to email me at marcel@codeofdoom.com. Thanks!

PS
Here is the source code

Marcel Design Patterns

  1. No comments yet.
  1. No trackbacks yet.