Describe:
Defines the skeleton of an algorithm in a method. Defer some of the steps to the child class. The template method allows subclasses to redefine some of the steps in the algorithm without changing the structure of the algorithm.
Hooks: Defines an empty method or the default method, providing the user subclass to cover the implementation of its own judgment and function according to the situation. Hooks can affect the flow of algorithms in an abstract class. It is optional to set the hook somewhere in the algorithm. Let subclasses have the ability to make some decisions about their abstract classes.
Class Diagram:
The following procedure simulates the process of making different beverages.
1. Definition of caffeinated beverages abstract class
Package Net.dp.templatemethod.barista; 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");} }
2. Realization of beverage abstract class
Package Net.dp.templatemethod.barista; public class Tea extends Caffeinebeverage {public void Brew () { System.out.println ("steeping the Tea"); Public void Addcondiments () { System.out.println ("Adding Lemon");} }
Package Net.dp.templatemethod.barista; public class Coffee extends Caffeinebeverage {public void Brew () { System.out.println ("dripping Coffee through F Ilter "); } public void Addcondiments () { System.out.println ("Adding Sugar and Milk");} }
3. Testing
Package Net.dp.templatemethod.barista; public class Beveragetestdrive {public static void Main (string[] args) { Tea tea = new Tea (); Coffee Coffee = new Coffee (); System.out.println ("\nmaking tea ..."); Tea.preparerecipe (); System.out.println ("\nmaking coffee ..."); Coffee.preparerecipe (); }}
Design mode-Template method