Design patterns in a comprehensible way-template method pattern

Source: Internet
Author: User

Mode motive

Template method pattern is a basic technique based on inheritance, and the structure and usage of template method pattern are also the core of object-oriented design. In the template method pattern, you can put the same code in the parent class and put different method implementations in different subclasses.
In the template method pattern, we need to prepare an abstract class that implements some of the logic in the form of concrete methods and concrete constructors, and then declares some abstract methods for subclasses to implement the remaining logic. Different subclasses can implement these abstract methods in different ways, thus having different implementations of the remaining logic, which is the intent of the template method pattern. The template method pattern embodies many important ideas of object-oriented, and is a mode with high frequency.

Pattern definition
Template method Pattern: Defines the skeleton of an algorithm in an operation, and delays some steps into subclasses, and the template method allows subclasses to redefine some specific steps of the algorithm without altering the structure of an algorithm. Template method is a kind of behavior-type pattern
The Template Method pattern:define The skeleton of a algorithm in a operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm ' s structure.
Frequency of Use:medium
UML diagram

Pattern structure
The template method pattern contains the following roles:
AbstractClass: Abstract class
Concreteclass: Specific sub-class

Pattern Analysis
A template method pattern is a behavioral pattern of a class, in which there is only an inheritance relationship between classes and no object affinity.
In the use of template method patterns, it is required to collaborate among designers who develop abstract classes and develop specific subclasses. A designer is responsible for giving the outline and skeleton of an algorithm, while others are responsible for the various logical steps of the algorithm. The methods for implementing these specific logical steps are called basic methods (Primitive method), and the methods that summarize these basic law methods are called template methods, and the name of the template method pattern comes from here.

Template method: A template method is a method of defining a general algorithm or a total behavior in an abstract class that combines basic operational methods.
Basic method: The basic method is the method to implement each step of the algorithm, is a part of the template method.
? Abstract method
? Specific methods (concrete method)
Hook method: "Hook" method and empty method

In the template method pattern, because of object-oriented polymorphism, the subclass object will overwrite the parent object at run time, and the methods defined in the subclass will override the methods defined in the parent class, so the basic method of the subclass will override the basic method defined in the parent class at run time, and the hook method of the subclass will override the parent class's Hook method. Thus, the implementation of the parent class method can be constrained by the hook method implemented in the subclass to implement the subclass's reverse control of the behavior of the parent class.

Pattern Instances and parsing
It would be useless to copy the wrong questions.-Template Method mode
System structure

TestPaper.cs

usingSystem;namespacetemplatemethodpattern{//The test paper of Jin Yong's novels    classTestpaper {//Question 1         Public voidTestQuestion1 () {Console.WriteLine ("Yang had to get, and later gave, refining into the sword, Dragon Sword of the Xuan Iron is [] a. Ball mill cast iron B. tinplate c. High-speed alloy steel D. Carbon fiber"); Console.WriteLine ("Answer:"+Answer1 ()); }        //Question 2         Public voidTestQuestion2 () {Console.WriteLine ("Yang, Chengying, Lu Matchless to eradicate the feeling of flowers, causing [] a. So that the plant no longer harms B. Extinction of a rare species C. destroying the ecological balance of the biosphere D. Desertification in the region"); Console.WriteLine ("Answer:"+Answer2 ()); }        //Question 3         Public voidTestQuestion3 () {Console.WriteLine ("Blue Phoenix caused the Huashan master, Peach Valley Six cents vomit not only, if you are a doctor, will give them what medicine [] A. Aspirin b. Bezoar jiedu tablets C. haloperidol d. Let them drink a lot of raw milk e. All right"); Console.WriteLine ("Answer:"+Answer3 ()); }        protected Virtual stringAnswer1 () {return ""; }        protected Virtual stringAnswer2 () {return ""; }        protected Virtual stringAnswer3 () {return ""; }    }}

TestPaperA.cs

usingSystem;namespacetemplatemethodpattern{//Student A copy of the test paper    classTestpapera:testpaper {//Question 1         Public New voidTestQuestion1 () {Base.        TestQuestion1 (); }        //Question 2         Public New voidTestQuestion2 () {Base.        TestQuestion2 (); }        //Question 3         Public New voidTestQuestion3 () {Base.        TestQuestion3 (); }        protected Override stringAnswer1 () {return "b"; }        protected Override stringAnswer2 () {return "a"; }        protected Override stringAnswer3 () {return "C"; }    }}

TestPaperB.cs

usingSystem;namespacetemplatemethodpattern{//Student B-copy of the test paper    classTestpaperb:testpaper {//Question 1         Public New voidTestQuestion1 () {Base.        TestQuestion1 (); }        //Question 2         Public New voidTestQuestion2 () {Base.        TestQuestion2 (); }        //Question 3         Public New voidTestQuestion3 () {Base.        TestQuestion3 (); }        protected Override stringAnswer1 () {return "D"; }        protected Override stringAnswer2 () {return "b"; }        protected Override stringAnswer3 () {return "a"; }    }}

Client: Customer Class

usingSystem;namespacetemplatemethodpattern{classProgram {Static voidMain (string[] args) {Console.WriteLine ("students a copy of the test paper:"); Testpaper Studenta=NewTestpapera ();            Studenta.testquestion1 ();            Studenta.testquestion2 ();            Studenta.testquestion3 (); Console.WriteLine ("Student B-copy of the test paper:"); Testpaper STUDENTB=NewTestpaperb ();            Studentb.testquestion1 ();            Studentb.testquestion2 ();            Studentb.testquestion3 ();        Console.read (); }    }}

Model Pros and cons
Advantages of the template method pattern
? The template method pattern formally defines the algorithm in a class, and its subclasses implement the processing of the details.
? The template method pattern is a basic technique for code reuse.
? The template method pattern results in a reverse control structure that invokes the operation of its subclasses through a parent class, adding new behavior through the extension of the subclass, in accordance with the "open and closed principle".

Disadvantages of the template method pattern
? Each of the different implementations needs to define a subclass, which leads to an increase in the number of classes, a larger system, and a more abstract design, but more in line with the "single Responsibility Principle", which improves the cohesion of the class.

Mode applicable environment
You can use the template method pattern in the following situations:
? Implement an invariant part of an algorithm at once, and leave the variable behavior to subclasses to implement.
? The public behavior in each subclass should be extracted and centralized into a common parent class to avoid code duplication.
? Some complex algorithms are segmented, and the invariant parts of the algorithm are designed as template methods and parent class concrete methods, and some of the details can be changed by their subclasses.
? controls the extension of the subclass.

"Statement and thanks"
This article, on the shoulders of many giants, draws on and cites many other works or writings that others have copyrighted, and is here to thank the former people for their contributions. And at the same time publish the quoted content, the original author or source (some of the content from the Internet can not be traced to the source, deeply regret).

"References"
Design mode-the basis of reusable object-oriented software author: [US] Erich gamma/richard Helm/ralph johnson/john vlissides Translator: Li Yingjun/Ma Xiaoxing/Cai Min/Liu Jianzhong and other machinery industry press
Refactoring-Improving the design of existing code author: Martin Fowler Translator: China Power Press, HOU-jie
"Agile software Development-principles, patterns and practices" Author: Robert C. Martin Tsinghua University Press
"Programmer's path to cultivation-from small to expert" by Andrew hunt/david Thomas Electronics Press
Head First design mode author: Freeman translator: O ' Reilly Taiwan company China Power Press
"Zen of Design Pattern" Author: Qin Xiaobo Machinery Industry Press
MSDN Webcast "C # Object-oriented design mode discussion on" lecturer: Li Jianzhong
Liu wei. design mode. Beijing: Tsinghua University Press, 2011.
Liu wei. Design pattern Training Tutorial. Beijing: Tsinghua University Press, 2012.
"Big Liar design Mode" Author: Geoscience Tsinghua University Press
C # Illustrated Tutorial Author: Solis Translator: Surin/Zhu Ye People's post and telecommunications press
"You must know. NET" Author: Wang Tao
. NET in Project author: Li Tianping Electronics Press
The Microsoft. NET Enterprise Application Architecture Design Author: (US) Esposito and other translators: Chen Lifu
http://www.dofactory.com/Patterns/Patterns.aspx. NET Design Patterns
Http://www.cnblogs.com/zhenyulu Blog Lu Zhenyu
Http://www.cnblogs.com/terrylee Blog Li Huijun
http://www.cnblogs.com/anlyren/Blog Anlyren
Http://www.cnblogs.com/idior Blog Idior
Http://www.cnblogs.com/allenlooplee blog Allen Lee
HTTP://BLOG.CSDN.NET/AI92 Blog ai92
http://www.cnblogs.com/umlonline/Blog Zhang
http://www.cnblogs.com/lovecherry/Blog Lovecherry

Design patterns in a comprehensible way-template method pattern

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.