Patterns of template methods for Java design patterns

Source: Internet
Author: User

Introduction to Template Method Patterns

Template method, as the name implies, is the general process of doing some tasks. If there are many self-introduction templates on the Web, the recommendation template, that is, the beginning and end of the content may be similar, and in the middle of the need for customers to modify the use. Design patterns originate from life, and template methods are born in a similar scenario. The template method is to write an algorithm framework in an operation, and defer some steps into subclasses, so that subclasses can redefine some specific steps of the algorithm without altering the structure of an algorithm.

design method of template method

template methods typically design an abstract class that internally defines some abstract methods that require subclasses to implement, because these methods may have different implementations for different subclasses and are therefore defined as abstract methods . In addition, there should be one or more template methods in the abstract class, that is, a fixed framework, and the modifier of this method is usually defined as final, to prevent subclasses from covering the template, because we think the template is fixed and cannot be modified . Within this fixed template method, the abstract method is called, which steps through the process of the algorithm. In general, subclasses are going to inherit this abstract parent class and implement the abstract methods within their own business logic.

features of the template method

The template method clearly delineated the change and invariant of a certain kind of business, made the process framework for a class of business, provided the common code for the subclass, and the behavior of the subclass was controlled by the parent class completely, and realized the maintainability and extensibility of the code. The parent class cannot be modified, the subclass can be extended, well conform to the design mode of the open and close principle-to modify the closed, to expand the opening.

Notice the difference between template method design pattern and abstract class design, abstract class This design pattern is the parent class to define some abstract methods, let the subclass to implement, so the subclass usually has more free space, and the template method is the parent class defines the algorithm framework, subclasses to implement the parent class of the abstract method, so the role of the subclass can affect the parent class.

examples of application of template methods Background Introduction

Suppose you want to make some beverage products now, for example, tea and coffee. The flow of tea and coffee can be divided into four steps, the first boiling water, the second baking ingredient, the third into the Cup, the fourth add seasoning. Usually the first and third steps are the same, so we can write the method directly in the parent class, and the second and fourth steps are different with the tea or coffee, so we design it as an abstract method for the subclass to implement. And these four steps are a fixed flow of drinks in general, so we wrap these four steps in a method, and set the modifier for this method to final, in case the subclass modifies it.

Template Method

The following first writes the code of the template method:


Package com.template;/** * Template Mode * Abstract base class, providing algorithmic framework for all subclasses * Business: Refreshing drink * @author ZZW * */public abstract class Refreshbeverage {/* * A template method for preparing beverages, specifying the algorithm framework *///block subclasses from making a copy of the template method public final void Preparebeveragetemplate () {//Step 1: Boil water boilwater ();//Step 2: Brew beverage ();///Step 3: Pour into the cup pourincup ();///Step 4: Add seasoning (Introduce the hook function, from the user's point of view, optional) if (Iscustomerwantcondiments ()) {addcondiments ();}} /* Hook, hook function * Provides a default or empty implementation * Specific subclasses can decide whether to hook and how to hook * Ask the user whether to add seasoning */protected Boolean iscustomerwantcondiments () {//default settings RE Turn true;} Abstract method, subclasses implement protected abstract void addcondiments ();p rivate void Pourincup () {//Pour into the cup System.out.println ("Pour into the cup");} Abstract methods, subclasses implement protected abstract void Brew ();p rivate void Boilwater () {//Boil water System.out.println ("boil Water");}



sub-class implementation

Because the specific implementation of tea and coffee is different, and can also use the hook function to determine whether the user needs to add seasoning, which makes the process more humane.

Tea:


Package com.template;/** * Specific implementation of TEA preparation * Subclass * @author ZZW * */public class Teabeverage extends Refreshbeverage {@Overridepro tected void Addcondiments () {//TODO auto-generated method StubSystem.out.println ("Add tea seasoning"); @Overrideprotected void Brew () {//TODO auto-generated method stubSystem.out.println ("Baking Tea");}}



Brew Coffee:



Package Com.template;public class Coffeebeverage extends Refreshbeverage {@Overrideprotected void addcondiments () {// TODO auto-generated Method StubSystem.out.println ("Add coffee seasoning"); @Overrideprotected void Brew () {//TODO auto-generated method stubSystem.out.println ("roasted coffee");}}



As Chinese tea is generally not spiced, so if the introduction of a Chinese tea, in the inheritance of tea, based on the addition of spices will be set to not add.



Package com.template;/** * Preparation of Chinese tea * No need to add seasoning * So select the hook function * Others will inherit tea production * @author Administrator * */public class Chineseteabever Age extends Teabeverage {@Overrideprotected Boolean iscustomerwantcondiments () {//TODO auto-generated method Stubreturn false;}}



hook function

A hook is actually a program segment that processes messages, and it is put into the system by a system call. Whenever a particular message is issued, the hook program captures the message before it reaches the destination window, i.e. the hook function gets control first. At this point the hook function can process (change) the message, or you can continue to pass the message without processing, and you can force the end of the message delivery.
For each type of hook the system maintains a chain of hooks, the most recently installed hooks are placed at the beginning of the chain, and the first installed hooks are placed at the end, that is, the first to gain control over the added. As mentioned in this blog post, whether or not to add seasoning is a hook function, it has the discretion to add seasoning.
If you specify a thread that is defined, it is a thread-specific hook, or a global hook if NULL is specified. Where the global hook function must be included in the DLL (dynamic-link library), the thread-specific hooks can also be included in the executable file. The hook function that gets control after processing the message, if you want the message to continue to pass, it must call the API function CallNextHookEx in the other SDK to pass it. The hook function can also discard the message by directly returning true, and block the delivery of the message.



usage Scenarios for template method Patterns

The template method can be used to implement an invariant part of an algorithm one time, and leave the variable part to the subclass to implement; The common code part of the subclass should be refined into the parent class to write well, prevent the code from repeating, control the extension of the subclass, the template method only allows to invoke the hook function at a specific point, This allows scaling only at these points.


Patterns of template methods for Java design patterns

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.