Template
Definition
Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.
UML class diagram
Participants
- AbstractClass
- defines abstract primitive operations that concrete subclasses define to implement steps of an algorithm
- implements a template method defining the skeleton of an algorithm. The template method calls primitive operations as well as operations defined in AbstractClass or those of other objects.
- ConcreteClass
- implements the primitive operations ot carry out subclass-specific steps of the algorithm
Sample code in Java
package com.hong.template; abstract class Template { public void templateMethod(){ methodOne(); methodTwo(); } public abstract void methodOne(); public abstract void methodTwo(); } class ExtendOne extends Template { @Override public void methodOne() { System.out.println("methodOne from ExtendOne."); } @Override public void methodTwo() { // TODO Auto-generated method stub System.out.println("methodTwo from ExtendOne."); } } class ExtendTwo extends Template { @Override public void methodOne() { System.out.println("methodOne from ExtendTwo."); } @Override public void methodTwo() { System.out.println("methodTwo from extendTwo."); } } public class Template_structure { public static void main(String[] args) { Template templateOne = new ExtendOne(); Template templateTwo = new ExtendTwo(); templateOne.methodOne(); templateOne.methodTwo(); templateTwo.methodOne(); templateTwo.methodTwo(); } }