1. Concepts
Defines the skeleton of an algorithm in an operation, and delays some steps to the subclass. The template method allows the subclass to redefine the specific steps of some algorithms without changing the algorithm structure.
2. Model
The template method mode is frequently used in programming and will not be explained in detail. Common models are as follows:
Using system; using system. collections. generic; using system. text; namespace templatemethod {public abstract class templatesuper // The parent class defines the algorithm framework {public void initialoperation () {console. writeline ("specific algorithm of the parent class. ");} Public abstract void abstractmethod ();} public class createtemplate1: templatesuper // inherits the parent class and implements Part of the algorithm 1 {public override void abstractmethod () {console. writeline ("subclass implementation part of algorithm 1") ;}} public class createtemplate2: templatesuper // inherits the parent class and implements Part of the algorithm 2 {public override void abstractmethod () {console. writeline ("subclass implementation part of algorithm 2") ;}} client: using system; using system. collections. generic; using system. text; namespace templatemethod {class program {static void main (string [] ARGs) {templatesuper tsuper; tsuper = new createtemplate1 (); tsuper. initialoperation (); tsuper. abstractmethod (); tsuper = new createtemplate2 (); tsuper. abstractmethod (); console. readline ();}}}
Result:
We can find that the template method mode is similar to the previous policy mode, and inherits the parent class to implement different algorithms. But they are different. From the definition, we can see that the template method mode is the skeleton of an algorithm in an operation, and some steps are delayed to the subclass. Rule mode: defines the algorithm family and encapsulates them separately so that they can be replaced with each other. This mode changes the algorithm and does not affect the customers who use the algorithm.
The difference between them is that the template method mode has an algorithm skeleton in the parent class, but it only delays some steps to be processed in the subclass. That is to say, the subclass only implements some algorithms. The policy mode only defines the algorithm family. The sub-classes are completely implemented, and the algorithms implemented by different sub-classes are completely different. That is, the whole is completed by sub-classes, and the algorithm is changed. The template method mode is partial implementation, and the policy mode is overall implementation, which is the difference between them.