Template mode is the skeleton of an algorithm defined in a method, and some steps are deferred to subclasses, and the template method allows subclasses to redefine some of the steps in the algorithm without altering the algorithm structure.
Template methods are common in many places, especially when we re-implement many frameworks, and many times we re-implement them based on the template approach.
Here is an example of a template method:
Caffeinebeverage.java
Public abstract class Caffeinebeverage { final void Preparerecipe () { boilwater ();; Brew (); Pourincup (); Addcondiments (); } abstract void Brew (); abstract void addcondiments (); void Boilwater () { System.out.println ("boiling water"); } void Pourincup () { System.out.println ("pouring into Cup");} }
Tea.java
public class Tea extends Caffeinebeverage { @Override void Brew () { System.out.println ("steeping the Tea"); } @Override void Addcondiments () { System.out.println ("Adding Lemon");} }
Coffee.java
public class Coffee extends Caffeinebeverage { @Override void Brew () { System.out.println ("Dripping coffe Throgh filter "); } @Override void Addcondiments () { System.out.println ("Adding Sugar and Milk");} }
The template method also has the implementation with hooks, I remember in the Shiro used to use the template method with hooks, this is not said.
Template method pattern of design pattern