Java “Template Method” pattern examples

Summary: This article presents a discussion of the Template Method Pattern, using Java source code examples to explain it.

The Template Method Pattern is one of the most simple design patterns around, and odds are you've been using it for almost as long as you've been writing object oriented code. In short, whenever you write a base class, and leave one or more methods to be implemented by derived classes, you're using the Template Method Pattern. Note that the implication here is that your base class is an abstract class, and the methods it specifically does not implement will be abstract methods.

Before I go on, here's a slightly more formal definition of the Template Method Pattern from the c2.com website:

Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method pattern lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.

The Template Method Pattern in Java

This template method is such a common design pattern that examples are easily found in the Java API. It's likely that any time you see a class that begins with the name "Abstract", you'll find some examples of the Template Method Pattern in action. Here are a few examples that come to mind:

AbstractTableModel
The AbstractTableModel defines most methods for handling data for the display of a JTable, but specifically leaves out the implementation of the getRowCount, getColumnCount, and getValueAt methods. When you create your own table model, it's common to extend the AbstractTableModel, and then implement these methods in your own class. The DefaultTableModel provides an implementation of these methods, so you can look to it for an example.
AbstractListModel
The AbstractListModel is very similar to the AbstractTableModel; it implements an interface (the ListModel interface), defines most methods of that interface, but leaves several methods for you to implement (getElementAt, getSize).

I haven't looked at each of the following classes, but here is a short list of other abstract Java classes I found in a quick API search:

  • AbstractStringBuilder
  • AbstractQueue
  • AbstractAction
  • AbstractButton
  • AbstractSet
  • AbstractMap
  • several more ...

As mentioned, you can guess just from their name that they are involved in an implementation of the Template Pattern.

Types of methods in a Template Method Pattern class

The Design Patterns book tells us that the Template Method typically has four types of methods that can be used in derived classes (subclasses):

  1. Complete methods that carry out basic functions for all child classes.
  2. Methods that are not filled in at all (abstract methods in Java).
  3. Methods that contain a default implementation that may be suitable for some subclasses, but which may need to be overridden for other subclasses.
  4. Methods that call any combination of abstract, partial, and concrete methods.

Let's take a look at a simple implementation of the Template Method Pattern in Java in the following example.

A Java Template Method Pattern example

It may help to see another implementation of the Template Method Pattern in Java, so to that end I've created a very small example here, using the ever-popular "Pizza store" theme.

If you've ever eaten a pizza, you know that a pizza comes with one or more toppings, including cheese, sausage, pepperoni, veggies, and more. Although the following design is far from ideal, you can imagine that in a Java program created to model a pizza store, you might have a Topping interface that would include the specification of many Topping methods. To keep my example simple, I'll just say that a Topping must have the following two methods:

public interface Topping
{
  public String getName();
  public float getWeightUsed();
}

Next, we'll create an abstract Java class that partially implements this interface:

/**
 * To keep this Template Method Pattern example simple,
 * I've excluded all the other Topping methods that would 
 * actually be needed, so I can focus on one abstract method 
 * in this class.
 */
public abstract class AbstractTopping implements Topping
{
  private String name;

  public AbstractTopping()
  {
    // assume some magic happens here where we connect to a database
    // to get our name, unitWeight, and numberOfPieces
  }
 
  public String getName()
  {
    return this.name;
  }

  /**
   * For inventory control and ordering purposes, we need to know the 
   * number of pieces used, as well as the total weight of this topping
   * that was used. The formula here might vary according to the
   * topping type, pizza size, and any requests for "extra" or "double"
   * toppings.
   */
  public abstract float getWeightUsed();
}

As you can see from that class, it should be easy enough for our abstract class to return the name of any topping, but the weight of a topping can end up being a complicated formula that varies according to topping type, pizza size, and other parameters, so rather than making this class have to have an algorithm for each topping type, we'll just let this class pass the actual implementation on to its sub-classes. So, this abstract Java class meets the definition of the Template Method Pattern: It implements some methods, while leaving other methods to be defined by child classes.

To complete our Java Template Method implementation, we'll also define two concrete classes that extend our abstract class. First, a CheeseTopping class that defines the getWeightUsed method:

public class CheeseTopping extends AbstractTopping
{
  /**
   * Implement this method in our own way.
   */
  public float getWeightUsed()
  {
    // implement our own magic formula here ...
    return 1.0f;
  }
}

And second, a SausageTopping class that also extends the AbstractTopping class, and provides its own implementation of the getWeightUsed method:

public class SausageTopping extends AbstractTopping
{
  /**
   * Implement this method in our own way.
   */
  public float getWeightUsed()
  {
    // implement our own magic formula here ...
    return 2.0f;
  }
}

Of course in the real world these methods would be much more complicated, but in an effort to keep this example simple, I'll leave it at this for now.

Summary: Template Method Pattern in Java

I hope this discussion and Java Template Method Pattern example have been helpful. If you have any questions or comments, please leave a note in the Comments section below, and I'll be glad to discuss this pattern more.