#
Template
This tutorial explains to you the design pattern named Template (which is a Structural Pattern).
#
Template Pattern - theory
Template Method Design Pattern in Java is used when we want to define some generic steps/tasks in an abstract master class, but the implementation of them separately in concrete child classes.
The Template Method Pattern is a very common technique for reusing code.
Take a look at the following UML diagram representing the Template Method design pattern (for my example):
#
Template Pattern - example
Here is an example of using the Template Design Pattern in Java:
package templatemethod.java.pattern.example;
public abstract class Enjoy {
abstract void playGame1();
abstract void playGame2();
//template method
public final void play(){
playGame1();
playGame2();
}
}
package templatemethod.java.pattern.example;
public class EnjoyInWinter extends Enjoy {
@Override
void playGame1() {
System.out.println("I GO SKIING.");
}
@Override
void playGame2() {
System.out.println("I BUILD a SNOWMAN.");
}
}
package templatemethod.java.pattern.example;
public class EnjoyInSummer extends Enjoy {
@Override
void playGame1() {
System.out.println("I GO SWIMMING.");
}
@Override
void playGame2() {
System.out.println("I PLAY SOCCER.");
}
}
package templatemethod.java.pattern.example;
public class TemplateMethodJavaPatternExample {
public static void main(String[] args) {
Enjoy summer = new EnjoyInSummer();
summer.play();
System.out.println("");
Enjoy winter = new EnjoyInWinter();
winter.play();
}
}
When you run this example you will receive the following result: