C # Design Pattern 13 Template method pattern (model mode pattern) "Behavioral"

Source: Internet
Author: User

Original: C # design Pattern 13 Template method pattern (model mode pattern) "Behavioral"

First, Introduction

"Structural" design patterns have been written, from today we began to talk about "behavioral" design patterns. Now we begin to talk about the first pattern of the "behavioral" design pattern, which is the "template method", in English, the name is: the pattern. Or the old routine, first look at the name. "Template Method" The first time I saw this name, my understanding is that there is a method called "Template Method", later in-depth study, feel the initial understanding is correct, you can also change the understanding method, there is a method contains a template, this template is an algorithm. In our real life there are many examples can be used to illustrate this pattern, take dumplings this thing, want to eat dumplings must go through three steps, the first step is "noodles", the second step is "bag stuffing", the third step is "boiled dumplings", these three steps is an algorithm, we want to eat to different noodles and stuffing dumplings, Any step in these three steps can be done, or you can fully define these three steps, let's take a look at the details of this pattern.

second, the template method model detailed introduction

2.1. Motive (motivate)

In the software construction process, it often has a stable overall operation structure for a task, but each sub-step has a lot of changing requirements, or because of inherent reasons (such as the relationship between the framework and the application) and the overall structure of the task can not be implemented simultaneously. How to flexibly deal with the change of sub-steps or the requirement of late realization under the premise of determining stable operation structure?

2.2. Intention (Intent)

Defines the skeleton of an algorithm in an operation, and delays some steps into subclasses.                                      The Template method allows subclasses to redefine some specific steps of the algorithm without altering the structure of an algorithm. --"Design pattern" GoF

2.3. Structure Diagram



2.4, the composition of the model

Template Method Pattern Participants:

(1), abstract class role (AbstractClass): Defines a template method (Templatemethod), in which the skeleton of an algorithm is included, The specific algorithm steps are the PrimitiveOperation1 method and the PrimitiveOperation2 method, and the subclass of the abstract class will redefine the PrimitiveOperation1 and PrimitiveOperation2 operations.

(2), Specific class roles (Concreteclass): Implements the PrimitiveOperation1 method and PrimitiveOperation2 method to complete the content associated with a particular subclass (Client) in the algorithm.

In the template method pattern, Templatemethod in AbstractClass provides a standard template that contains two methods for PrimitiveOperation1 and PrimitiveOperation2, The content of these two methods can be overridden by the client according to its own needs.

2.5. Concrete implementation of template method pattern

After understanding the template method definition, the natural implementation template method is not difficult, the following to eat dumplings in life as an example to achieve Template method mode. In real life, the steps of making dumplings are roughly the same, if we define a class for each type of dumpling, so that there are many identical code in each class, in order to solve this problem, our general idea is to abstract the same part into the abstract class to define, specific subclasses to achieve specific different parts, This idea is also the formal template method of implementation of the essence, the implementation of the Code as follows:

1 namespaceimplementation of template method pattern2 {3     /// <summary>4     ///delicious than dumplings, comfortable than the upside, I like to eat my father's dumplings, today take dumplings this thing to see the implementation of the template method5     /// </summary>6     classClient7     {8         Static voidMain (string[] args)9         {Ten             //now want to eat green noodles, pork and onion stuffing dumplings OneAbstractClass fan =NewConcreteclass (); A fan. Eatdumplings (); -  - Console.WriteLine (); the             //after a while, I began to want to eat orange noodles, leek and egg stuffing dumplings -Fan =NewConcreteClass2 (); - fan. Eatdumplings (); -  +  - Console.read (); +         } A     } at  -  -     //This type is abstract class role--abstractclass, the definition of making dumplings algorithm skeleton, here are three steps, of course, there can be multiple steps, depending on the actual needs of -      Public Abstract classAbstractClass -     { -         //This method is the template method, the method contains the algorithm steps to make dumplings, the template method can return the result, can also be void type, depending on the situation in          Public voideatdumplings () -         { to             //and Polygon + Makingdough (); -             //Bag Stuffing the makedumplings (); *             //boiled dumplings $ boileddumplings ();Panax Notoginseng  -Console.WriteLine ("dumplings are so delicious! "); the         } +  A         //to eat dumplings the first step must be "face"---this method is equivalent to a step in the algorithm the          Public Abstract voidMakingdough (); +  -         //Want to eat dumplings the second is "dumplings"---this method is equivalent to a step in the algorithm $          Public Abstract voidmakedumplings (); $  -         //Want to eat dumplings The third part is "boiled dumplings"---this method is equivalent to a step in the algorithm -          Public Abstract voidboileddumplings (); the     } - Wuyi     //the type is specific class role--concreteclass, I want to eat green dough, pork and onion stuffing dumplings the      Public Sealed classConcreteclass:abstractclass -     { Wu         //to eat dumplings the first step must be "face"---this method is equivalent to a step in the algorithm -          Public Override voidMakingdough () About         { $             //I want to face green, green health, you can customize this step -Console.WriteLine ("add celery juice to the dough, and the good side is green."); -         } -  A         //Want to eat dumplings the second is "dumplings"---this method is equivalent to a step in the algorithm +          Public Override voidmakedumplings () the         { -             //I want to eat pork and onion stuffing, in this step can be customized $Console.WriteLine ("Farm pork and peasant onion, made into stuffing"); the         } the  the         //Want to eat dumplings The third part is "boiled dumplings"---this method is equivalent to a step in the algorithm the          Public Override voidboileddumplings () -         { in             //I want to eat dumplings cooked in the big iron pot, the taste of home, in this step can be customized theConsole.WriteLine ("use my big wok and big wood to cook dumplings"); the         } About     } the  the     //the type is specific class role--concreteclass2, I want to eat orange dough, leek egg stuffing dumplings the      Public Sealed classConcreteclass2:abstractclass +     { -         //to eat dumplings the first step must be "face"---this method is equivalent to a step in the algorithm the          Public Override voidMakingdough ()Bayi         { the             //I want the noodles to be orange and add the carrot juice. You can customize it in this step.  theConsole.WriteLine ("add carrot juice to the dough, and the right side is orange."); -         } -  the         //Want to eat dumplings the second is "dumplings"---this method is equivalent to a step in the algorithm the          Public Override voidmakedumplings () the         { the             //I want to eat leek egg stuffing, in this step can be customized -Console.WriteLine ("Farm eggs and peasant leek, made into stuffing"); the         } the  the         //Want to eat dumplings The third part is "boiled dumplings"---this method is equivalent to a step in the algorithm94          Public Override voidboileddumplings () the         { the             //not required here theConsole.WriteLine ("can be boiled with ordinary gas and non-stick pot");98         } About     } -}

This mode is very simple, the notes are very detailed, see the notes should be almost, there is a point is that the template method inside the algorithm steps, can have the default implementation, or can not be implemented, in C # can be an abstract method, of course, the template method can have a return value, you can also have no return value.

three, the template method to achieve the main points of the mode:

Template method mode is a very basic design pattern, which has a large number of applications in object-oriented system. It uses the most concise mechanism (the polymorphism of virtual function) to provide flexible extension for many application frameworks, and is the basic implementation structure of code reuse. In addition to the flexibility to respond to changes in the sub-steps, the "Don't Call me, let me calls you" (Do not invoke me, lets me invoke you) "The reverse control structure is a typical application of template method."

Template Method Pattern applicable case:

(1), one-time implementation of an invariant part of the algorithm, and the variable behavior is left to subclass to achieve.

(2), the public behavior of each subclass should be extracted and centralized into a common parent class to avoid code duplication.

(3), control sub-class extension. The template method only allows expansion at a specific point, while the template section is stable.

   Template Method Pattern Features:

(1), Templatemethod mode is a very basic design mode, in the object-oriented system in a large number of applications. It provides flexible extensibility points for many application frameworks with the simplest mechanism (base, polymorphic), and is the basic implementation structure for code reuse.

(2), in the specific implementation aspect, the virtual method called by Templatemethod can have the implementation, or can have no implementation (abstract method or virtual method). However, it is generally recommended that they be set to the protected method so that only subclasses can access them.

(3), template method mode through the extension of the sub-class to add new behavior, in line with the "open and close principle."


iv. implementation of template patterns in. NET

This mode is used extensively in control design, for example: the control has its own life cycle, the Page object also has its own life cycle, the application Application object also has its own life cycle, each phase of this life cycle is actually the template method contains each step, These phase steps are included in a method, which is the "template method". Let's say the control, because the written control may need to be customized by the developer, so in the control we have defined the control rendering, the skeleton of the action, but some custom requirements, need to defer to the extension of the control developer to decide.

When we are working on Windows applications, we use Windows controls, how Windows controls are displayed on Windows Form, a OnPaint method is needed to draw the controls, here OnPaint is a sub-step of a virtual method, This is a template method design pattern. If we don't rewrite this onpaint method, it will have a basic default implementation, drawing an empty form. Here we do not call the OnPaint method, but the application run enters the message loop structure of windows, and paint is a message. When we move the window, it causes the paint event to occur and causes the OnPaint function to be called, which is a reverse invocation. Of course, there are many other sub-steps that can provide extensibility points, such as OnClose, and many of them are virtual methods that start with the template method pattern. This content is very complex, it does not use a template method in the call all the sub-step method, it is actually the whole template method is placed in the structure of a message loop, We can think of the structure of the message loop as the Templatemethod public non-virtual method inside the template method.

v. Summary

This is the end of the day, it's time to cook, and our "template method" pattern has been finished. There was a person, of course, who wrote the program, said, if a person uses object-oriented language to write programs, but has not used the "template method" mode, I am sure that this person wrote the program is not object-oriented, but the use of object-oriented language only. Although a bit harsh and mean, but not unreasonable, this model is very simple, it may be intentional or unintentional use of the model has been used, perhaps just do not know its name.

C # Design Pattern 13 Template method pattern (model mode pattern) "Behavioral"

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.