Template Method pattern defines the skeleton of an algorithm, and defer some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.
Implementation checklist
abstract template class – a) defines abstract primitive operations that concrete subclasses define to implement steps of an algorithm. b) implements a template method which defines the skeleton of an algorithm. The template method calls abstract primitive operations and other operations.
concrete class – implements the primitive operations.When a concrete class and its the template method code is called, primitive operations and other operations inside the template method will be executed.
Step 1: create an template class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package net.tecbar.designpattern.template; public abstract class Shape { public void fillColor() { System.out.println("fill color"); } public void colorBorder() { System.out.println("color border"); } public abstract void calculateArea(); public void execute() { // template method colorBorder(); calculateArea(); fillColor(); } } |
Step 2: create concrete subclass which extends the template class
1 2 3 4 5 6 7 8 9 10 11 12 |
package net.tecbar.designpattern.template; public class Circle extends Shape { @Override public void calculateArea() { System.out.println("circle area = PI * ridius * ridius"); } } |
1 2 3 4 5 6 7 8 9 10 11 12 |
package net.tecbar.designpattern.template; public class Rectangle extends Shape { @Override public void calculateArea() { System.out.println("rectangle area = width * length"); } } |
Step 3 demo client
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package net.tecbar.designpattern.template; public class TemplateMethodDemo { public static void main(String[] args) { Shape circle = new Circle(); Shape rectangle = new Rectangle(); circle.execute(); // execute template method System.out.println("=========="); rectangle.execute(); // execute template method } } |
output:
1 2 3 4 5 6 7 8 9 |
color border circle area = PI * ridius * ridius fill color ========== color border rectangle area = width * length fill color |
Pingback: Software Design Patterns