Template method is better understood, is to avoid code redundancy, implementation of code to take the function. For example, the most common tea and coffee, two have a lot in common, all need to boil water, all need to pour into the cup, then these repeated methods can be drawn out, placed in the parent class, as for the different methods, write an abstract class, so that different subclasses to rewrite the parent class.
Code
Template class
Package Template;public Abstract class Template {public void prepare () {boilwater (); Brew ();p Ourcup (); Boil public void Boilwater () {System.out.println ("boil Water");} public abstract void Brew ();
Pour in the cup public void Pourcup () {System.out.println ("Pour into the cup");}}
Brew Coffee
Package Template;public class Getcoffee extends template {@Overridepublic void Brew () {System.out.println ("Brew Coffee");}}
Tea
Package Template;public class Gettea extends template {@Overridepublic void Brew () {System.out.println ("tea");}}
Test Class
Package Template;public class Test {public static void main (string[] args) {//tea brewing Gettea tea = new Gettea (); Tea.prepare ();// Brewed coffee Getcoffee coffee=new getcoffee (); Coffee.prepare ();}}
Results
Boil the water and pour the tea into the cup and pour the water into a cup of coffee.
Java design Pattern----Template Method pattern