1 Public Abstract classRefreshbeverage {2 3 Public Final voidpreparebeveragetemplate () {4 5 Boilwater ();6 Brew ();7 Pourincup ();8 if(Isaddcondiments ()) {9 addcondiments (); Ten } One } A //a hook function that provides a default or null implementation; A subclass can decide for itself whether to hook and how to hook - protected Booleanisaddcondiments () { - the return true; - } - Private voidBoilwater () { -System.out.println ("1 ... "); + } - protected Abstract voidBrew (); + A Private voidPourincup () { atSystem.out.println ("3 ... "); - } - protected Abstract voidaddcondiments (); -}abstract base class that provides an algorithmic framework for all subclasses
1 Public classCoffeeextendsrefreshbeverage{2 3 @Override4 protected voidBrew () {5System.out.println ("2.coffee bubble Mode");6 7 }8 9 @OverrideTen protected voidaddcondiments () { OneSystem.out.println ("4.coffee"); A - } - the } - - Public classTeaextendsrefreshbeverage{ - + @Override - protected voidBrew () { +System.out.println ("2.teaaa"); A } at - @Override - protected voidaddcondiments () { - - } - //Subclasses Select the Mount hook function in the form of overrides in @Override - protected Booleanisaddcondiments () { to return false; + } -}Implementation Class
1 Public classTest {2 3 /**4 * Implementation elements of template method mode5 * Prepare an abstract class that implements part of the logic in the form of a concrete method,6 * Then declare some abstract methods to the subclass to implement the remaining logic,7 * Use the hook method to give subclasses greater flexibility. 8 * Finally, the method always constitutes an immutable template method9 * Ten * Applicable Scenarios One * 1. The algorithm or operation follows similar logic A * 2. When refactoring (the same code is abstracted into the parent class) - * 3. Important and complex algorithms, core algorithm design as template algorithm - * the * Advantages - * 1. Good encapsulation 2. Good reusability 3. Shielding details 4. Easy Maintenance - * Disadvantages - * Inheritance + * */ - Public Static voidMain (string[] args) { +Refreshbeverage Coffee =NewCoffee (); A coffee.preparebeveragetemplate (); at - System.out.println (); -Refreshbeverage tea =NewTea (); - tea.preparebeveragetemplate (); - } -}Test Class
Template mode for Java design patterns