Java template method design pattern

Dictionary meaning template: A shaped piece of rigid material used as a pattern for processes such as cutting out, shaping, or drilling.

Java template design pattern comes under behavioural design patterns. In template design pattern an abstract class is used to define a template (steps to execute an algorithm). Now, its subclasses can provide the implementation of template methods.

Note: We have to be careful in calling the subclass methods. Method invocation should be in the same way as they are defined in the abstract class.

Let’s discuss template design pattern with below example. We are considering here an algorithm to play a game. To play a game steps will be common like initialize, start play and end play. Here we have to note that operations invocation should be in the same way as they are defined in the abstract class because start play cannot be called before initialize operation.

Example

Game.java

package com.w3schools;
 
public abstract class Game {
   abstract void initialize();
   abstract void startPlay();
   abstract void endPlay();
 
   public final void play(){
      initialize();
      startPlay();
      endPlay();
   }
}

Cricket.java

package com.w3schools;
 
public class Cricket extends Game {
	@Override
	void initialize() {
		System.out.println("Cricket game initialized.");
	}
 
	@Override
	void startPlay() {
		System.out.println("Cricket game started.");
	}
 
	@Override
	void endPlay() {
		System.out.println("Cricket game finished.");
	}	
 
}

Tennis.java

package com.w3schools;
 
public class Tennis extends Game {
	@Override
	void initialize() {
		System.out.println("Tennis game initialized.");
	}
 
	@Override
	void startPlay() {
		System.out.println("Tennis game started.");
	}
 
	@Override
	void endPlay() {
		System.out.println("Tennis game finished.");
	}	
 
}

BridgePatternTest.java

package com.w3schools;
 
public class BridgePatternTest { 
   public static void main(String args[]){	   
      Game game = new Cricket();
      game.play();
      System.out.println();
      game = new Tennis();
      game.play();
   }
}

Output

Cricket game initialized.
Cricket game started.
Cricket game finished.
 
Tennis game initialized.
Tennis game started.
Tennis game finished.