Template method Mode

Source: Internet
Author: User

Definition: Defines the skeleton of an algorithm in a method. Some of the steps are deferred to subclasses. Template methods enable subclasses to redefine some of the steps in a method without altering the algorithm and structure.

One: main points

The template method defines the steps of the algorithm, delaying the implementation of these steps to subclasses.

The template method pattern provides us with an important technique for code reuse.

Abstract classes of template methods can define concrete methods, abstract methods, and hooks.

Hooks are a way of doing things in an abstract class, or just doing the default. Subclasses can choose to not overwrite him.

To prevent subclasses from changing the algorithm in the template method, you can declare the template method as final.

The Hollywood principles tell us that the decision-making power is placed in a high-level module to determine how and when to invoke a lower-layer module.

Both the policy pattern and the template method are used in the encapsulation algorithm, one with the combination, one with the inheritance.

The factory method is a special version of the template method

Two: Examples of template methods

When you hit the code, you get tired of having a cup of coffee or a cup of tea. In fact, whether coffee or tea in the rush of time are fastidious. This is not the focus in this document. The following describes the process of brewing coffee and brewing:

The difference between the two types of tea is the following code:

1PublicClassCoffee2{3PublicvoidPreparerecipe ()4{5//Boiling water6Boilwater ();7//Brew Coffee8Brewcoffeegrinds ();9//Pour into a teacup10Pourincup ();11//Add sugar and coffee12Addsugarandmilk ();13}14PublicvoidBoilwater ()15{Console.WriteLine ("Boiling water");17}1819PublicvoidBrewcoffeegrinds ()20{Console.WriteLine ("Brew Coffee");22}2324PublicvoidPourincup ()25{Console.WriteLine ("Pour into the cup");27}2829PublicvoidAddsugarandmilk ()30{Console.WriteLine ("Add sugar and milk");32}33}3435PublicClassTea36{37PublicvoidPreparerecipe ()38{39//Boiling water40Boilwater ();41//Tea42Steepteabag ();43//Pour into a teacup44Pourincup ();45//Add lemon46Addlemon ();47}48PublicvoidBoilwater ()49{Console.WriteLine ("Boiling water");51}5253PublicvoidSteepteabag ()54{Console.WriteLine ("Tea");56}5758PublicvoidPourincup ()59 {60 Console.WriteLine (  " Pour in the cup " ); 61 }62 63 public void {65 Console.WriteLine ( " plus lemon  "); 66  67}     
View Code

In the object-oriented language, it is to be reused, and now the method of boiling water and bringing into the cup is obviously repetitive, which does not conform to the panchayat-reuse of the object village. Comparing the two approaches, it takes four steps to make the same use of a base class, and the different parts are implemented by themselves. The class diagram is as follows

If we look at it carefully, our coffee and tea and the addition of coffee and milk are almost identical. So you can continue to abstract, the abstract approach is roughly the same:

In fact, that is our template method. Here's a look at the class diagram of the template method pattern:

Three, template Method class diagram

From the class diagram, we can see that we put common methods in abstract classes for reuse. Put the uncertain method into the concrete class so that the concrete class can construct its own method well. In addition, there is an important point is that whether it is a well-constructed method or an abstract method, it will be loaded into a Templatemethod method. As is the case with our usual projects, the approximate steps need to be: Demand analysis--------the most basic process of coding--and testing. But every step of the way, may be different, but the process of doing a few steps of the project is basically the same, the steps are abstracted into a template, the time to do the project, all follow this step to do. This is our template method pattern. We'd better make our tea and coffee here.

Base class Code:

PublicAbstractClasscoffeeinbeverage1{PublicvoidBoilwater () {Console.WriteLine ("  boiling water  ); public voidpublic void Pourincup () {Console.WriteLine ( " Pour into the cup  ");} public abstract void< Span style= "color: #000000;" > Brew (); public abstract void< Span style= "color: #000000;" > Addcondiments ();}               

Coffee code:

Class coffee1:coffeeinbeverage1{    void Brew () {Console.WriteLine (" Punch coffee "void  Addcondiments () {Console.WriteLine (" add sugar and Milk ");}         

Tea code:

Class tea1:coffeeinbeverage1{    void Brew () {Console.WriteLine (" tea "void  Addcondiments () {Console.WriteLine (" add lemon ");}}         
Four, the problem of the template method attention

In the tea and coffee above, now it seems to be able to drink, but one problem is that some people drink coffee like without any seasoning. Then we simply add to the guest, certainly will be angry. To meet this requirement, the design pattern provides the solution-using hooks. Specifically what is the hook, we have a small time in the textbook there is a monkey fishing Moon pictures:

Each monkey will not only be pulled by other monkeys, but will also hold out a hand to pull other monkeys. But the last hand did not pull the other monkeys, but still want to stretch, in case you can't touch the moon.

Also do not know the method can be used to get, but there are corresponding methods, the specific time used to get, what time can not be used, according to the conditions to judge.

Here's a look at how hooks are used in Template method mode:

Base class Code:

PublicvoidPreparerecipe () {boilwater ();        Brew (); Pourincup ();// There is a judgment method to add seasoning if (Wantcondiments ()) {addcondiments ();}} ///<summary>////    Add a method to determine if seasoning is required/   //</summary>// <returns> </returns> public Virtual bool wantcondiments () { return true;}   

In subclasses, you can override the Wantcondiment () method in a different way class. The standard used to indicate whether to add a seasoning, in this method note that the virtual keyword must be added so that override overrides are used in subclasses. Here's how to do it in coffee:

BOOL wantcondiments ()   {       false;}  

Here is the test code:

Class program  {      void Main (stringnew Coffee1 (); Coffeninbeverage.preparerecipe (); Console.readkey (); } }

Output Result:

found that the spices had been removed.

Comparison of template method pattern and strategy model and factory method

When looking at the template method time, it is easy to think of the factory method. Because they all let the concrete implementation put in the subclass, but the factory method mainly is produces the product, then goes to apply the product. The template method is a few of the steps in a dependent subclass, and the specific steps are already written in the base class.

The same template method pattern and policy pattern are encapsulation algorithms. However, each policy in the policy mode is a separate class. You can change the policy at any time. Template method Mode Although also encapsulates the algorithm, in fact, mainly in the encapsulation step, the specific implementation is based on the individual subclasses.

In addition, the template approach model involves a Hollywood principle:

Don't call me, I'll take the initiative to call you.

The role of playing Hollywood in the template method pattern is abstract, and the subclass is the actor's role.

It is generally necessary to call a method in a subclass that has already been defined in the template and, when needed, to actively contact the steps, preferably in a subclass, not to invoke methods in the abstract class to prevent a messy call to the subclass and the parent class.

Template method Mode

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.