Template methods (Template method) mode
Prepare an abstract class, implement part of the logic in the form of concrete methods and concrete constructs, and then declare some abstract methods to force subclasses to implement the remaining logic. Different subclasses can implement these abstract methods in different ways, thus having different implementations of the remaining logic. This is the purpose of the template method pattern.
Many people may not think that the template method pattern is actually one of the most common patterns in all patterns, and that many people may have used the template method pattern without realizing that they have used the pattern. Template method pattern is based on the basic technology of inheritance code reuse, the structure and usage of template method pattern is also the core of object-oriented design.
Template method patterns require the development of collaboration between abstract classes and designers of specific subclasses. A designer is responsible for the outline and skeleton of an algorithm, while others are responsible for the logical steps of the algorithm. The methods that represent these specific logical steps are called the basic methods (primitive method), and the method of combining these basic methods is called the template approach (template method), which is the name of the design pattern.
Second, the template method pattern structure
The static structure of the template method pattern is shown in the following illustration.
There are two roles involved:
The abstract template (abstractclass) role has the following responsibilities:
One or more abstract operations are defined in order for subclasses to be implemented. These abstract operations are called basic operations, and they are the constituent steps of a top-level logic.
Defines and implements a template method. This template method is generally a concrete method, which gives the skeleton of a top-level logic, and the logical composing step is deferred to the subclass implementation in the corresponding abstract operation. It is also possible for top-level logic to invoke some specific methods.
The specific template (Concreteclass) role is the responsibility:
Implements one or more abstract methods defined by the parent class, which are the constituent steps of a top-level logic.
Each abstract template role can have any number of specific template roles to correspond to, and each specific template role can give the different implementations of these abstract methods (i.e., the constituent steps of the top-level logic) so that the implementations of the top-level logic vary.