Overview:
Template Method (templatemethod): definesAlgorithmAnd delay some steps to the subclass.
Templatemethod allows the subclass to redefine certain steps of an algorithm without changing the structure of an algorithm.
Practicality:
1. Implement the unchanged part of an algorithm at one time, and leave the variable behavior to the subclass for implementation.
2. Public behaviors in each subclass should be extracted and concentrated in a public class to avoidCodeDuplicate.
First, identify the differences in the existing code and separate the differences into new operations.
Finally, replace these different codes with a template method that calls these new operations.
3. Control subclass Extension
Class diagram:
Structure display code:
1. define abstract parent class
Abstract Class Abstractclass
{
/// <Summary>
/// Abstract behavior, which is implemented by sub-classes
/// </Summary>
Public Abstract Void Primitiveoperation1 ();
Public Abstract Void Primitiveoperation2 ();
/// <Summary>
/// The template method provides a logical framework, but the abstract operations in the template must be implemented by subclass.
/// </Summary>
Public Void Templatemethod ()
{
Primitiveoperation1 ();
Primitiveoperation2 ();
Console. writeline ( "" );
}
}
2. Define subclass of the Implementation Algorithm
Class Concreteclassa: abstractclass
{
Public Override Void Primitiveoperation1 ()
{
Console. writeline ( " Method 1 for Class A to abstract the parent class " );
}
Public Override Void Primitiveoperation2 ()
{
Console. writeline ( " Method 2 for Class A to abstract the parent class " );
}
}
Class Concreteclassb: abstractclass
{
Public Override Void Primitiveoperation1 ()
{
Console. writeline ( " Method 1 for Class B to abstract the parent class " );
}
Public Override Void Primitiveoperation2 ()
{
Console. writeline ( " Method 2 for Class B to abstract the parent class " );
}
}
3. Client call
/// <Summary>
/// Test Template Method
/// </Summary>
Static Void Testtemplatemethod ()
{
Abstractclass C;
C = New Concreteclassa ();
C. templatemethod ();
C = New Concreteclassb ();
C. templatemethod ();
Console. Read ();
}
Summary:
The template method is the simplest code reuse and encapsulation, which is used in many system libraries to make your system structure more reasonable.