The template method pattern is defined as:
The skeleton or step of an algorithm is defined in a method, and some steps are deferred to subclasses to implement. Template methods allow subclasses to redefine some of the steps in an algorithm without changing the structure of the algorithm.
The template method defines the process order of an operation in the base class, it is possible to ensure that the step is sequential, that some of the steps are implemented in the base class, and that the concrete implementation of some of the changed steps is given to subclasses to implement, thus reaching a delay in some steps into subclasses, One of the biggest benefits of template methods is the ability to set up a business process that can be executed in a strict order, controlling the execution of the entire algorithm.
This method defines the algorithm as a set of steps, and all the steps that want the subclass to be a custom implementation are defined as abstract methods. The characteristic of an abstract base class is that the template method is typically set to final, so that subclasses are prevented from overwriting the algorithm, the same actions or steps are implemented directly in the base class, and some of the changed steps are set to abstract subclasses to complete.
Java Implementation Example
class Diagram:
/**
* Business process template, provide the basic framework *
* Public
abstract class Basetemplate {public
abstract void Part1 ();
public abstract void Part2 ();
public abstract void Part3 ();
Here in order to strictly test the results, use final cannot be rewritten public
final void Usetemplatemethod () {
part1 ();
Part2 ();
Part3 ();
}
/** * Template Implementation 1/public class Templatemethod extends-basetemplate {@Override
public void Part1 () {System.out.println ("template Method 1");
@Override public void Part2 () {System.out.println ("template Method 2");
@Override public void Part3 () {System.out.println ("template Method 3"); }
}
/**
* Template Implementation 2
* @author Stone * * */Public
class TemplateMethod2 extends Basetemplate {
@ Override public
void Part1 () {
System.out.println ("template Method One");
@Override public
void Part2 () {
System.out.println (template method);
}
@Override public
void Part3 () {
System.out.println ("template Method");
}
public class Test {public
static void Main (string[] args) {
basetemplate tm = new Templatemethod ();
Tm.usetemplatemethod ();
System.out.println ("");
Basetemplate tm2 = new TemplateMethod2 ();
Tm2.usetemplatemethod ();
}
Print:
Template Method 1
Template Method 2
Template Method 3
Template Method One template method template method
33