Template Method Pattern : Defines the skeleton of an algorithm in an operation, and delays some specific steps into subclasses.
The template method pattern allows subclasses to redefine some specific steps of the algorithm without altering the structure of an algorithm.
Structure diagram:
AbstractClass is an abstract class that defines and implements a template method, which generally gives the top-level logical skeleton, while the concrete logical composition is in the corresponding abstract
The operation. Defer to the subclass and complete the different implementations.
Features of the template method:
1. Move the invariant behavior to the parent class, removing the duplicate code for the subclass.
2. When a sequence of steps consists of a process that requires execution, these steps are the same at the highest level, but some steps may be implemented differently, you might consider using a template method pattern.
Example:
Let's say we scrambled eggs in fried rice. No, it should be oil first.
classmakeeggrice{ Public: voidShoweggrice (); VirtaulvoidAddoil (); Virtual voidFireegg (); Virtual voidFirerice (); };classlishifueggrice{ Public: Virtual voidAddoil () {cout<<"a lot of oil"<<Endl; } Virtual voidFireegg () {cout<<"Fire 2 Eggs"<<Endl;} ......}
Template method pattern of design pattern