In an abstract class, the way in which methods are executed is publicly defined, subclasses can be implemented as required, but calls are made in the manner defined in the abstract class, typical applications such as banking processes, and brewing beverage processes. The following is a simple example, with boiling water brewing beverage, divided into four steps: boil, brew beverage, pour the drink into the cup, add seasoning.
1. Template abstract class
Points: 1) abstract class 2) Final modified template method
Public Abstract classRefreshtemplate { Public Final voidRefresh () {//Boil the waterBiolwater (); //Processed BeverageBrew (); //Pour the drink into the cupPourincup (); //Add Seasoningaddcondiments (); } Private voidBiolwater () {System.out.println ("Boil the Water"); } protected Abstract voidBrew (); Private voidPourincup () {System.out.println ("Pour the drink into the cup"); } protected Abstract voidaddcondiments ();}
2, coffee class, Inherit template class, rewrite brewing, add seasoning method
Public class extends refreshtemplate { protectedvoid Brew () { System.out.println ("brew coffee with boiling water") ); } protected void addcondiments () { System.out.println ("Add milk and sugar to the coffee");} }
3. Tea class, Inherit template class, rewrite brewing, add seasoning method
Public class extends refreshtemplate { protectedvoid Brew () { System.out.println ("Soak in boiling water for 5 minutes "); } protected void addcondiments () { System.out.println ("Add lemon");} }
4. Testing
Public class Model { publicstaticvoid main (string[] args) { // refreshtemplate refresh = new Coffee (); New Tea (); Refresh.refresh (); }}
Using the dynamic binding of Java (upward transformation), the final template method of the parent class is invoked to ensure that execution is performed in the manner defined by the abstract class.
Java design Pattern (iii) template mode