How to implement Template Method pattern in Java?

Let’s say you have created an application with two complex forms :

One for managing products.

Another for managing user of the products.

You have a single form ‘ProductForm’ for managing a product and a single form ‘UserForm’ for managing a user.

You want to perform three levels of validation for both the forms:

  • Input Validation
  • Business Rules Validation
  • Database Validation

These steps are the same for both ProductForm and UserForm though the implementations differ. Also you want to perform all these in a single call , say on calling a method validate(). Also you want to perform some validations common to both the forms as part of the same validate() call.

Here comes Template Method pattern for rescue.

Template Method pattern defines a template of operations which can be implemented in different ways by different subclasses.

Let’s dive into the code , let’s see client code first:

package behavioural.templatemethod.pattern;

public class Client {

	public static void main(String a[]) {

		Validator productValidator = new ProductFormValidator();

		Validator userValidator = new UserFormValidator();


As you see I have created two validators one for ProductForm and another for UserForm and I have invoked the same method validate() on both of them. The method validate() is called the Template Method since it provides a template of operations in sequence (an algorithm) .These operations are declared as abstract in the super class and are defined in the sub classes.

Here is the class which has the Template Method validate():

package behavioural.templatemethod.pattern;

public abstract class Validator {

	public void validate() {

		if (isValidationRequired()) {



	private void doCommonValidation() {

		System.out.println("Performing validation common to all forms");


	protected abstract boolean isValidationRequired();

	protected abstract void doDatabaseValidation();

	protected abstract void doBusinessRulesValidation();

	protected abstract void doInputValidation();

In the above code , the template method validate() defines the below algorithm:

Does the form need validation?

If Yes do the following:

  • Do common validations first
  • Do input validation specific to the form next
  • Do business rules validation specific to the form next
  • Do database validation specific to the form at the last

If No , do nothing.

The method doCommonValidation() performs common validations which are the same for both the forms. This is defined in the abstract class itself.

The other steps are implemented by the ProductFormValidator and the UserFormValidator according to their needs. The subclasses themself decide whether they need the validation or not . (This can be set dynamically by the client , that is not implemented here for simplicity)

Here is the ProductFormValidator:

package behavioural.templatemethod.pattern;

public class ProductFormValidator extends Validator {

	protected void doDatabaseValidation() {

		System.out.println("Performing database validation for Product");


	protected void doBusinessRulesValidation() {

		System.out.println("Performing business rules validation for Product");


	protected void doInputValidation() {

		System.out.println("Performing input validation for Product");

	protected boolean isValidationRequired() {
		return true;


Similar logic is written for UserFormValidator.

Here is the output of the client code:

Performing validation common to all forms
Performing input validation for Product
Performing business rules validation for Product
Performing database validation for Product

Performing validation common to all forms
Doing input validation for User
Doing business rules validation for User
Doing database validation for User

That’s it.

The Gang of Four define the Template method pattern as:

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

He suggests to use the pattern:

– To implement the invariant parts of an algorithm once and leave it up to subclasses to implement the behaviour that can vary

(in our case , the common validations are implemented in the base class and the form specific validations are implemented in the sub classes)

– When common behaviour among subclasses should be factored and localized in a common class to avoid code duplication. ..You first identify the differences in the existing code and then separate the differences into new operations. Finally , you replace the differing code with a template method that calls one of these new operations.

(Similar to the first definition except that you do it as part of refactoring code rather than designing it upfront)

– to control subclass extensions. You can define a template method that calls ‘hook’ operations at specific points, thereby permitting extensions only at those points.

(“Hook operations means methods which have a default implementation in the super class. Mostly they are empty (so the method becomes an optional implementation for subclasses). This can be overridden by subclasses but is not mandatory. Subclasses can decide whether they want to implement that method or not “)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s