[C ++ design mode] template method mode
Template mode: defines the algorithm skeleton in an operation and delays some steps to the subclass.
According to the example in headfirst design mode, the algorithm framework (process) of tea and coffee is the same, but some algorithms are implemented differently, and some are the same.
We can encapsulate a common algorithm framework as a virtual base class, declare the same algorithm as non-writable (static), and declare different algorithms as pure virtual functions to be implemented by the subclass.
You can use the hook () function to process small differences in the algorithm framework.
Here, we may think of the Policy mode. The rule mode also treats different algorithms that can be changed and those that are not easily changed, but the most fundamental difference between the rule mode and the template method mode is:
The policy mode uses a combination of classes to keep unchanged algorithms in the original class, but encapsulates the algorithms to be overloaded as a virtual base class separately. Subclass implements its own version, in this way, the original class is
Different API subclasses can be combined to call different algorithms.
The template method mode uses class inheritance to encapsulate an algorithm framework (STEP) as a virtual base class, and the algorithm framework cannot be covered. Subclass can only implement different steps. You can also introduce the hook () function to fine-tune the algorithm framework. The principle of the hook () function is very simple. The hook () function of the base class can be defined as null or some operations. The subclass can overload the hook () function of the base class.
The following is the template method mode without hook () hooks:
Class CaffeineBeverage // caffeine beverage {public: void PrepareRecipe () // caffeine beverage brewing method {BoilWater (); // boil the water to Brew (); // PourInCup (); // pour the caffeine drink into the cup AddCondiments (); // Add seasoning} void BoilWater () {std: cout <boil the water <std: endl ;} virtual void Brew () = 0; void PourInCup () {std: cout <pour coffee into the cup <std: endl;} virtual void AddCondiments () = 0 ;}; class Coffee: public CaffeineBeverage {public: void Brew () {std: cout <brewed Coffee with boiling water <std: endl;} void AddCondiments () {std: cout <sugar and milk <std: endl ;}}; class Tea: public CaffeineBeverage {public: void Brew () {std :: cout <soak tea leaves in boiling water <std: endl;} void AddCondiments () {std: cout <add Lemon <std: endl ;}}; int main (void) {std: cout <Coffee: <std: endl; Coffee c; c. prepareRecipe (); std: cout <std: endl; std: cout <brewed Tea: <std: endl; Tea t; t. prepareRecipe (); return 0 ;}