Template Method template method mode
1. Definition
Template Method mode defines an operation inAlgorithmAnd delay some steps to the subclass. The template method allows the subclass to redefine certain steps of an algorithm without changing the structure of an algorithm.
2. Description
What is "template "? The template is a specific method in this mode. This method sets a set of steps for implementing an algorithm. Any steps can be abstract and implemented by sub-classes. This ensures that the algorithm structure remains unchanged and is partially implemented by sub-classes.
The template method mode implements the unchanged part of an algorithm at one time (for example, the algorithm implementation step), and leaves the variable behavior to the subclass for implementation. It helps us to remove duplicates in similar methods contained in sub-classes of the same class hierarchy.Code.
The unchanged behavior in the template method mode consists of the following:
I. Call methods and call sequence;
Ii. Rewrite abstract methods that must be overwritten by subclass;
Iii. Hook methods that subclass may override;
3. UML
In the UML diagram, the templatemethod in the parent class is an abstract method, which calls four methods in a certain order-primitiveopertion1, primitiveopertion2, concreteopertion, and hook. primitiveopertion1 and operator are abstract methods, child classes are required to be implemented based on specific conditions, but the overall framework of the algorithm is controlled by the templatemethod method in the parent class.
4. Use
For the client, how does one use a class structure that implements the template method mode?
The PHP code is as follows:
$ Subclass2 = NewSubclass2 ();
$ Subclass2->Templatemethod ();
5. Conclusion
The template method mode is a relatively simple design mode, which is also common and should be mastered.
References: reconstruction and Model
Head first design model