Design problem
Template Method is a behavioural pattern which describes the common algorithm while subclasses implement steps of this algorithm. That means this pattern lets subclasses implement steps of an algorithm without changing the algorithm's skeleton.
As the example of the Template Method, we will consider the working process.
The algorithm contains three steps - go to work, work, go home.
Suppose all workers go to work and go home identically. A working routine is different depending on a worker’s qualification. We can use any profession, but the algorithm remains the same.
The template method pattern
An abstract base class implements standard algorithm steps and can provide a default implementation for custom steps. Specific subclasses provide the concrete implementation each of these step.
Template Method has the following components:
Abstract Class describes primitive operations and the template method itself which calls primitive operations
Concrete Class implements the primitive operations
This pattern is actively used in JDK.
Practice example
To demonstrate how the Template Method works, create the abstract class Worker which describes the working routine and add the template method:
public abstract class Worker {
public void work() {
goToWork();
workingProcess();
goHome();
}
public void goToWork() {
System.out.println(“= I'm going to work sadly =");
}
public void goHome() {
System.out.println("= I'm going home happy =");
}
public abstract void workingProcess();
}
The common algorithm of actions is already determined. Now, we will create two concrete classes: Programmer and Actor.
public class Programmer extends Worker {
public void workingProcess() {
System.out.println(" > I'm a programmer");
System.out.println(" > I drink coffee");
System.out.println(" > I write code");
System.out.println(" > I drink coffee again");
System.out.println(" > I write code again");
}
}
public class Actor extends Worker {
public void workingProcess() {
System.out.println(" > I'm an actor");
System.out.println(" > I read a scenario");
System.out.println(" > I get used to role ");
System.out.println(" > I play a role");
}
}
In the Demo class we create programmer and actor instances and call the template method :
public class TemplateMethodDemo {
public static void main(String[] args) {
Worker programmer = new Programmer();
Worker actor = new Programmer();
programmer.work();
actor.work();
}
}
Conclusion
Template Method is applicable in the following cases:
When the behaviour of an algorithm can vary, you let subclasses implement the behaviour through overriding
When you want to avoid code duplication, implementing variations of the algorithm in subclasses
When you want to control the point that subclassing is allowed.