Template Method pattern analogy
There should be such a scene in the memory of the Post-80s: The teacher tests the questions on the blackboard and asks us to copy the questions and then make the answers. Now, we can directly send a test paper so that we can directly write the answer on the test paper. Now, this form of test is actually the template method mode (templatemethod )!
Template Method pattern intent
The template method mode (templatemethod) definesAlgorithmAnd delay some steps to the subclass. The template method mode allows subclass to redefine certain steps of an algorithm without changing the structure of an algorithm.
Template Method pattern class diagram
Template Method implementation
/// <Summary>
/// Abstract the template and define and implement a specific template method. This method provides a skeleton of the top-level logic,
/// The logical composition step is postponed to the subclass implementation in the corresponding abstract operation.
/// </Summary>
Abstract class testpaper
{
/// <Summary>
/// Abstract behavior, implemented in subclass
/// </Summary>
Public abstract void answer ();
///
// template method. The logical skeleton is provided.
///
Public void templatemethod ()
{< br> console. writeline ("what do you think about Zhu Liit's blog? ");
answer ();
}< BR >}
///
// my exam: abstract method for implementing parent class definition
///
class mytestpaper: testpaper
{< br> Public override void answer ()
{< br> console. writeline ("Good! ");
}< BR >}
///
// your exam: Different implementations are provided, make the implementation of the top-level Logic different
///
class yourtestpaper: testpaper
{< br> Public override void answer ()
{< br> console. writeline ("pretty good! ");
}< BR >}
/// <Summary>
/// Template method mode client application
/// </Summary>
Class Program
{
Static void main (string [] ARGs)
{
// Questionnaire
Testpaper paper;
// My questionnaire
Paper = new mytestpaper ();
Paper. templatemethod ();
// Your questionnaire
Paper = new yourtestpaper ();
Paper. templatemethod ();
Console. Read ();
}
}
Template Method mode Summary
The template method mode prepares an abstract class, implements the general logic in the form of a specific method, and declares some abstract methods to force the subclass to implement the remaining logic. Different sub-classes can implement these abstract methods in different ways to implement the rest logic differently. That is to say, first develop a top-level logic and leave the details of the logic to specific sub-classes for implementation.
Original blog post on Zhu Liit:ArticleAddress: http://www.zhuli8.com/sjms/TemplateMethod.html