C # design Pattern Series: Template method pattern

Source: Internet
Author: User

Introduction

Referring to the template, you can not help but think of life "CV template", "Paper template", "Word in the template", etc., in real life, the concept of templates is-there is a prescribed format, and then everyone may according to their own needs or circumstances to update it, such as resume template, The format of the downloaded resume template is the same, but after we download the resume template we can fill in the different content according to our own situation to complete our own resume. In design mode, template method pattern in template and life template concept is very similar, let us describe in detail the definition of template method, you can according to the concept of template in life to understand the definition of template method.

Introduction to Template Methods

Definition of template Method pattern

The skeleton of an algorithm in an operation is defined, and some steps are deferred to subclasses, so that the subclass can not change the structure of an algorithm to redefine some specific steps of the algorithm

Structure diagram of pattern of imitation method

The composition of the pattern

AbstractClass is abstract class, in fact, is an abstract template, defines and implements a template method, this template method is generally a concrete method, it gives a top-level logical skeleton, and the logical composition of the steps in the corresponding abstract operation, deferred to the sub-class implementation, Top-level logic may also invoke some specific methods

Concreteclass implements one or more abstractions defined by the parent class, and each abstractclass can have any number of concreteclass corresponding to it. Each concreteclass can have different implementations of these abstract methods, which are the constituent steps of top-level logic, so that the implementation of the top-level logic varies


Looking at the definition of the template method and the structure diagram, let's look at how the code is used

Title: To class after the teacher on the blackboard out of homework, each student should copy the topic.

First Edition no mode

    // <summary>    // student Armour    // </summary>     Public classMethodA { Public voidTestQuestion1 () {Console.WriteLine ("question One "" A. correct b error c no solution"); Console.WriteLine ("Answer: b"); } Public voidTestQuestion2 () {Console.WriteLine ("question two "" A. correct b error c no solution"); Console.WriteLine ("Answer: A"); } Public voidTestQuestion3 () {Console.WriteLine ("question three "" A. correct b error c no solution"); Console.WriteLine ("Answer: C"); }    }// <summary>    /// students have    // </summary>     Public classMethodB { Public voidTestQuestion1 () {Console.WriteLine ("question One "" A. correct b error c no solution"); Console.WriteLine ("Answer: b"); } Public voidTestQuestion2 () {Console.WriteLine ("question two "" A. correct b error c no solution"); Console.WriteLine ("Answer: A"); } Public voidTestQuestion3 () {Console.WriteLine ("question three "" A. correct b error c no solution"); Console.WriteLine ("Answer: C"); }    }// <summary>    // Client    // </summary>    classprogram {Static voidMain (string[] args) {Console.WriteLine ("student A's Questions:"); MethodA A =NewMethodA ();            A.testquestion1 ();            A.testquestion2 ();            A.testquestion3 (); Console.WriteLine ("The student has the question:"); MethodB b=NewMethodB ();            B.testquestion1 ();            B.testquestion2 ();        B.testquestion3 (); }    }
View Code

Can see the content of the high degree of acquaintance, in addition to different answers, there is no difference, such code error-prone, difficult to maintain, learning the template method after the revision

Second Edition

 // <summary>    // abstract class    // </summary>     Public Abstract classtestquestion { Public voidTestQuestion1 () {Console.WriteLine ("question One "" A. correct b error c no solution"); Console.WriteLine ("Answer:"+ Anster1 ()); } Public voidTestQuestion2 () {Console.WriteLine ("question two "" A. correct b error c no solution"); Console.WriteLine ("Answer:"+anster2 ()); } Public voidTestQuestion3 () {Console.WriteLine ("question three "" A. correct b error c no solution"); Console.WriteLine ("Answer:"+ Anster3 ()); } Public Virtual stringAnster1 () {return""; } Public Virtual stringAnster2 () {return""; } Public Virtual stringAnster3 () {return""; }    }// <summary>    // student Armour    // </summary>     Public classmethoda:testquestion { Public Override stringAnster1 () {return"a"; } Public Override stringAnster2 () {return"b"; } Public Override stringAnster3 () {return"C"; }    }// <summary>    // Client    // </summary>    classprogram {Static voidMain (string[] args) {Console.WriteLine ("student A's Questions:"); Testquestion A =NewMethodA ();            A.testquestion1 ();            A.testquestion2 ();        A.testquestion3 (); }    }
View Code

Y introduction of Template method pattern, the readability of the code is increased, the immutable code is abstracted to the parent class, the subclass needs to fill in the answer is OK

Advantages and disadvantages of template method patterns

Advantages:

    1. Code reuse implemented
    2. Flexibility to respond to changes in sub-steps in accordance with the open-closed principle

disadvantage : Because of the introduction of an abstract class, if the implementation of too much, the need for users or developers to spend more time to clarify the relationship between classes.

Attached: in. Net Template method is also a lot of applications, such as when we are developing a custom Web control or WinForm control, we only need to override some of the methods of a control summary

Here, the introduction of the template method is finished, the template method pattern in the abstract class defines the algorithm implementation steps, the implementation of these steps to defer to the specific subclass to implement, so that all subclasses reuse the parent class code, so template method pattern is based on inheritance of a code to implement the reuse of the technology.

C # design Pattern Series: 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.