Template Pattern is a Behavioral Pattern that contains template methods for storing the algorithm steps. These algorithm steps are divided into sub classes. This method uses abstract methods for implementation. Template pattern is referred as "The Hollywood Principle" and the sub classes of the template can be overridden using final keyword.
Advantages
The logic of the system can be modified easily.
Template methods can be represented using customized hooks.
Algorithm steps can be kept in sub classes.
Conceptual
figure
AbstractClass - characterizes unique primitive operations that solid subclasses characterize to execute the ventures of a calculation. Abstract class actualizes a layout strategy, which characterizes the skeleton of a calculation. The format technique calls primitive operations in addition to the operations characterized in AbstractClass.
ConcreteClass : actualizes the primitive operations to do subclass-particular strides of the calculation. At the point when a solid class is known, the layout technique code will be executed from the base class. While for every strategy utilized inside, the format technique will be known as the usage from the determined class.
Examples
Creating an abstract class Sports and making it as abstract.
[java]public abstract class Sports
{
abstract void initialize();
abstract void sPlay();
abstract void ePlay();
//template method
public final void play()
{
//initialize the game
initialize();
//start game
sPlay();
//end game
ePlay();
}
}
[/java]
Creating a class Hockey and extending the class Sports.
[java]
public class Hockey extends Sports
{
void ePlay()//overrides the class method
{
System.out.println("Hockey Game Finished!");
}
void initialize()//overrides the class method
{
System.out.println("Hockey Game Initialized! Start playing.");
}
void sPlay()//overrides the class method
{
System.out.println("Hockey Game Started. Enjoy the game!");
}
}[/java]
Creating a Tennis class and extending the class Sports.
[java]public class Tennis extends Sports
{
void ePlay()//overrides the class method
{
System.out.println("Tennis Game Finished!");
}
void initialize()//overrides the class method
{
System.out.println("Tennis Game Initialized! Start playing.");
}
void sPlay()//overrides the class method
{
System.out.println("Tennis Game Started. Enjoy the game!");
}
}[/java]
Creating a TemplatePattern class.
[java]
public class TemplatePattern
{
public static void main(String[] args)
{
Sports game = new Hockey();//creating object for Sports class
game.play();
System.out.println();
game = new Tennis();
game.play();
}
}[/java]
Output
The result will be as follows.
[java]
Hockey Game Initialized! Start playing.
Hockey Game Started. Enjoy the game!
Hockey Game Finished!
Tennis Game Initialized! Start playing.
Tennis Game Started. Enjoy the game!
Tennis Game Finished!
[/java]
Summary
Key Points
Template Pattern - Default implementation can be provided.
Template Pattern - Algorithms can be easily implemented.