Template Method pattern: defines the skeleton of an algorithm in an operation, and delays 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. The template method is a type of behavior pattern.
The template method mode is a kind of behavior mode. In its structure, there is only an inheritance relationship between classes, and there is no object association relationship.
In the use of the template method mode, collaboration is required between the designers who develop abstract classes and develop specific child classes. One designer is responsible for providing the outline and skeleton of an algorithm, while other designers are responsible for providing the logical steps of this algorithm. The method that implements these specific logical steps is called the basic method, and the method that summarizes these basic methods is called the template method. The name of the template method mode comes from here.
Template Method: A template method is defined in an abstract class and combines basic operation methods to form a general algorithm or a general operation method.
Basic method: the basic method is to implement each step of the algorithm and is part of the template method.
Abstract Method)
Concrete Method)
Hook method: Hook method and empty Method
Hook method ):
Public void template ()
{
Open ();
Display ();
If (isprint ())
{
Print ();
}
}
Public Boolean isprint ()
{
Return true;
}
The typical abstract class code is as follows:
Public abstract class abstractclass
{
Public void templatemethod () // Template Method
{
Primitiveoperation1 ();
Primitiveoperation2 ();
Primitiveoperation3 ();
}
Public void primitiveoperation1 () // basic method-Specific Method
{
// Implementation code
}
Public abstract void primitiveoperation2 (); // basic method-abstract Method
Public void primitiveoperation3 () // basic method-Hook method
{
}
}
The typical subclass code is as follows:
Public class concreteclass extends abstractclass
{
Public void primitiveoperation2 ()
{
// Implementation code
}
Public void primitiveoperation3 ()
{
// Implementation code
}
}
In the template method mode, due to object-oriented polymorphism, The subclass object will overwrite the parent class object at runtime, and the methods defined in the subclass will also overwrite the methods defined in the parent class, therefore, when the program is running, the basic method of the specific subclass will overwrite the basic method defined in the parent class, and the hook method of the subclass will also overwrite the Hook method of the parent class, in this way, the implementation of the parent class method can be constrained by the Hook method implemented in the subclass to implement reverse control of the parent class behavior.
Template Method Mode