C # Design Pattern 9: Template method

Source: Internet
Author: User

Template method

A template method is a method that defines the steps of an algorithm and allows subclasses to provide implementations for one or more steps.

Examples of brewing coffee and tea in this example illustrate:

Explain the steps of brewing coffee and tea, you can see the steps of brewing coffee and tea, very similar, first look at the code that does not apply the template method:

The code of tea is similar, it is not released. One of their bad places is that the algorithms are scattered across classes, and there is a repetition of the code.

 Public Abstract classcaffeinebeverage//Design an abstract class that encapsulates the algorithm { Public voidBoilwater () {Console.WriteLine ("Boil Water"); }         Public voidPourincup () {Console.WriteLine ("pour in cup"); }         Public voidpreparerecipe ()//encapsulation algorithm, this is the template method.            {Boilwater ();            Brew ();            Pourincup ();        Addcondiment (); }         Public Abstract voidBrew ();//specific implementations to be implemented in subclasses Public Abstract voidaddcondiment ();//specific implementations to be implemented in subclasses} Public classTealogic:caffeinebeverage { Public Override voidBrew () {Console.WriteLine ("Brew Tea"); }         Public Override voidaddcondiment () {Console.WriteLine ("Add some lemon"); }    }     Public classCoffelogin:caffeinebeverage { Public Override voidBrew () {Console.WriteLine ("Brew coffe ..."); }         Public Override voidaddcondiment () {Console.WriteLine ("add some milk and sugar ..."); }    }

A template method defines an algorithm step and allows one or more of the subclasses to provide steps.

Template method Definition: Define the skeleton of the algorithm in one method, and defer some steps into the subclass. The template method can redefine some of the steps in the algorithm without changing the structure of the algorithm in the subclass.

At the same time, abstractclass internal definition of a hook method-a virtual method, you can decide whether to rewrite in the subclass, to achieve the purpose of the hook. The existence of hooks allows subclasses to have the ability to hook up different points of the algorithm, not to be hooked up, to be determined by the subclass itself.

//applying hooks in template methods     Public Abstract classAnotherkindofcoffeinebeverage { Public voidBoilwater () {Console.WriteLine ("Boil Water"); }         Public voidPourincup () {Console.WriteLine ("pour in cup."); }         Public Virtual BOOLcustomerwantcondiment ()//virtual method: Represents a hook {return true; }         Public Abstract voidBrew ();  Public Abstract voidaddcondiment ();  Public voidPreparerecipe () {boilwater ();            Brew (); if(Customerwantcondiment ()) {addcondiment ();        } pourincup (); }    }    //a scenario for applying a hook method     Public classAnotherkindoftea:anotherkindofcoffeinebeverage { Public Override BOOLcustomerwantcondiment () {returnGetcustomerinput (). Equals ("y"); }         Public Override voidBrew () {Console.WriteLine ("dropping coffe through filter."); }         Public Override voidaddcondiment () {Console.WriteLine ("add some condiment."); }        Private stringGetcustomerinput () {Console.WriteLine ("would some lemon with your tea? (y/n)"); varinput =Console.ReadLine (); returnInput?.        ToLower (); }    }

About hooks, it's a principle: when you have to provide a step in a template method, make an abstract method in the base class, and if the step is optional, make the virtual method, the hook.

Hooks can allow subclasses to implement an optional part of the algorithm, or the subclass can ignore this hook when the hook is less important to the implementation of the subclass. Another use of hooks is to allow subclasses to have an opportunity to react to certain upcoming steps in a template method. Hooks can also give subclasses the ability to make decisions about their abstract classes.

The most important point: some methods in an abstract class are optional, and for these optional methods, hooks are made, rather than abstract methods, so that the load on the subclass can be mitigated.

New design principles: Hollywood design Principles-don't call (call) us, I'll call (call) you.

Hollywood principles and template approach

The relationship between the two is quite obvious: when we design the template method, we tell the subclass, "Don't call us, we'll call you."

The relationship between the Hollywood principle and the dependency inversion principle:

C # Design Pattern 9: Template method

Related Article

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.