---Template method pattern of big talk design pattern

Source: Internet
Author: User

In the process of learning Java, we must have heard the design pattern of the term, in the industry there is such a word, if you can master 23 design patterns, then you are Daniel!

Okay, no more nonsense, today I share with you one of the 23 design patterns Template Method Design pattern

First we need to know what is the template method design pattern?

The template method design pattern is defined as an algorithm skeleton in an operation, and some implementation steps are deferred to subclasses. The template method allows subclasses to redefine some of the steps in the algorithm without changing the structure of the algorithm.

Why use a template method to design patterns?
The template method pattern is a relatively simple design pattern, but it is a basic technique for code reuse, which is especially important in the class library, following the refactoring principle that "abstract classes should have as much behavior as possible and should have as little data". As a template method to define in the parent class, the method is used in the definition of the abstract method, and only look at the parent of the abstract method is not know how to deal with, the actual processing is the subclass, in the subclass to implement the specific functions, so the different sub-class execution will come to different implementation results, However, the process is still customized by the parent class. This is the essence of the template approach, the formulation of the algorithm skeleton, so that the sub-class concrete implementation.

Under what circumstances is it used?
      --The algorithm or operation follows similar logic
  
   --When refactoring (extracting the same code into the parent class)

   --important, complex algorithms, core algorithms designed as template algorithms

Let's see how we can implement the template method design pattern.
We use a beverage machine as an example of the prototype, each beverage machine can produce a different beverage, like a beverage machine can make coffee and can make tea
If: The steps to make coffee are as follows: The steps to make tea are as follows:
1. Boil the water 1. Boil the water
2. Brew coffee in boiling water 2. Boil the tea in boiling water for 5-6 minutes
3. Pour the coffee into the cup 3. Pour the tea into the cup
4. If sugar or milk 4. Add the lemon or not add anything
So, from the background above, we make coffee and make tea in the steps 1 3 is exactly the same, and 2 4 is the individual steps of each
All we can do is design a template to standardize the production process.
/** Abstract Type Beverage machine template class*/ Public Abstract classTemplate {/** Template method for the preparation of beverages * Encapsulates a common algorithm framework for all subclasses*/     PublicFinalvoidDrivetemplate () {//This template must be final decorated, because subclasses cannot be allowed to modify the template framework, only to modify specific steps//1. Boil the waterBoilwater (); //2. Processed beverageblew (); //3. Pour into the cupPourincup (); //4. Enter Seasoningaddcondiments (); }
}
As the code above is defined as a template for the production of drinks, the specific steps are listed
Because our steps 1 and 3 are the same, we can define the implementation method as private to reduce the complexity of the code, whereas steps 2 and 4 can be defined as abstract methods whose implementation is done by its subclasses
Such as:
/** Basic method to boil the water*/    Private voidBoilwater () {System. out. println ("Boil the water"); }        /** Basic method, pour into the cup*/    Private voidPourincup () {System. out. println ("pour into the cup"); }    /** Abstract basic methods to add seasonings*/     Public Abstract voidaddcondiments (); /** Abstract Basic method of processing beverages*/     Public Abstract voidBlew ();


such as making coffee
/** The specific implementation of coffee preparation*/ Public classCoffee extends Template {//Add Seasoning@Override Public voidaddcondiments () {System. out. println ("add sugar and milk"); }    //Brewed Coffee@Override Public voidblew () {System. out. println ("Brew Coffee in boiling water"); }}

Or the making of tea.
/** Specific implementation of tea preparation*/ Public classTea extends Template {//Add Seasoning@Override Public voidaddcondiments () {System. out. println ("Add Lemon"); }    //Tea Brewing@Override Public voidblew () {System. out. println ("Soak the tea for 5 minutes with 80 degrees of hot water"); }    }

So we can see the results very clearly in the test class.
//Test Class Public classTest { Public Static voidMain (string[] args) {System. out. println ("Preparation of coffee"); Template T1=NewCoffee ();        T1.drivetemplate (); System. out. println ("Coffee Preparation Complete"); System. out. println ("====================="); System. out. println ("Preparation of tea"); Template T2=NewTea ();        T2.drivetemplate (); System. out. println ("Preparation of tea finish"); }}

Test results

Of course, what if we now have another demand? Is that I do not want to add anything when making tea, when we use the above method is unable to complete, this time we will lead to
Another noun in the template method design pattern, the hook function
We can use the hook function to determine whether we want to perform a certain step of the operation
Such as:
/** Abstract Type Beverage machine template class*/ Public Abstract classTemplate {/** Template method for the preparation of beverages * Encapsulates a common algorithm framework for all subclasses*/     PublicFinalvoidDrivetemplate () {//This template must be final decorated, because subclasses cannot be allowed to modify the template framework, only to modify specific steps//1. Boil the waterBoilwater (); //2. Processed beverageblew (); //3. Pour into the cupPourincup (); //hook function to determine (e.g. tea does not want to add seasoning)        if(Isright ()) {//4. Enter Seasoningaddcondiments (); }    }        /** Basic method to boil the water*/    Private voidBoilwater () {System. out. println ("Boil the water"); }        /** Basic method, pour into the cup*/    Private voidPourincup () {System. out. println ("pour into the cup"); }    /** Abstract basic methods to add seasonings*/     Public Abstract voidaddcondiments (); /** Abstract Basic method of processing beverages*/     Public Abstract voidblew (); //The hook function determines whether the user wants to perform certain functions     PublicBoolean isright () {return true; }    }

If you don't want to add anything when making tea, we just need to rewrite the hook function in the sub-class of tea making.
/** Specific implementation of tea preparation*/ Public classTea extends Template {//Add Seasoning@Override Public voidaddcondiments () {System. out. println ("Add Lemon"); }    //Tea Brewing@Override Public voidblew () {System. out. println ("Soak the tea for 5 minutes with 80 degrees of hot water"); }    //rewrite the hook function to change its value@Override PublicBoolean isright () {return false; }}

The results of this implementation

So we're done with our needs.

The above is the template method design mode of content, and other design patterns will be in the follow-up after learning to share with you ~ ~
Note: I am also a beginner, so write a bad place to look at you Daniel do not blame, there are insufficient places also hope to point out, welcome to discuss!



---Template method pattern of big talk design 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.