Click “like” to see, form a habit, the public account search [dime technology] pay attention to more original technical articles. This article has been included in GitHub org_Hejianhui /JavaStudy.

preface

  • 23 design modes for shorthand
  • The singleton pattern
  • Factory Method pattern
  • Abstract Factory pattern
  • The Builder/Builder pattern
  • Prototype mode
  • Flyweight mode
  • The facade pattern
  • Adapter mode
  • Decorator pattern
  • Observer mode
  • Strategy mode
  • Bridge mode
  • Updates continue at……

Here are 23 design patterns to memorize quicklyTemplate method patternRelated content.

The schema definition

Define the algorithmic skeleton of an operation, deferring some steps to subclasses. Template Method allows subclasses to redefine specific steps of an algorithm without changing its structure.

Redefine the content of a template in a subclass without changing the template structure. The template method pattern is based on inheritance;

The pattern is implemented as follows:

package com.niuh.designpattern.templatemethod.v1;

/** * template method mode */
public class TemplateMethodPattern {
    public static void main(String[] args) {
        AbstractClass tm = newConcreteClass(); tm.templateMethod(); }}/ / abstract classes
abstract class AbstractClass {

    // Template method
    public void templateMethod(a) {
        specificMethod();
        abstractMethod1();
        abstractMethod2();
    }

    // Specific methods
    public void specificMethod(a) {
        System.out.println("A concrete method in an abstract class is called...");
    }

    // Abstract method 1
    public abstract void abstractMethod1(a);

    // Abstract method 2
    public abstract void abstractMethod2(a);
}

// Concrete subclass
class ConcreteClass extends AbstractClass {

    public void abstractMethod1(a) {
        System.out.println("The implementation of abstract method 1 is called...");
    }

    public void abstractMethod2(a) {
        System.out.println("The implementation of abstract method 2 is called..."); }}Copy the code

The following output is displayed:

Concrete methods in abstract classes are called... Abstract methods1The implementation is called... Abstract methods2The implementation is called...Copy the code

Problem solved

  • Improve code reuse

Put the same part of the code in an abstract parent class, and different code in different subclasses

  • Reverse control is achieved

Reverse control is realized by calling the operations of its subclasses by a parent class and extending the different behaviors by the concrete implementation of subclasses & conforming to the “Open close Principle”

In the process of object-oriented programming, it is common to encounter such a situation: when designing a system, the key steps required by the algorithm are known, and the execution sequence of these steps is determined, but the specific implementation of some steps is unknown, or the implementation of some steps is related to the specific environment.

Patterns of

The template method pattern requires attention to collaboration between abstract classes and concrete subclasses. It uses the polymorphism technique of virtual functions and the “don’t call me, let me call you” reverse control technique. Now let’s introduce their basic structure.

Example is given to illustrate

Instance profiles

The design procedure of studying abroad is realized by template method mode.

Analysis: studying abroad formalities through the following process: general information for school, apply for admission, passport or exit card is dealt with private and notarization, apply for a visa, physical examination, booking a flight, prepares to pack to reach target schools, etc., some of the business of schools is the same, but some business varies from school to school so suit to use the template method pattern to implement.

In this example, let’s define oneStudyAbroad, which contains a TemplateMethod TemplateMethod(), which contains various basic methods in the process of handling the procedures of studying abroad. Some methods can be implemented in abstract classes because the processing of different countries is the same, but some methods are different in different countries. Must be implemented in its specific subclass (e.g. StudyInAmerica). If you add another country, you simply add a subclass, whose structure is shown in Figure 2.

Using the step

Step 1: Define an abstract class for studying abroad

abstract class StudyAbroad {
    // Template method
    public void templateMethod(a) {
        lookingForSchool(); // For school information
        applyForEnrol();    // Application for admission
        applyForPassport(); // Handle passport, exit card and notarization
        applyForVisa();     // Apply for a visa
        readyGoAbroad();    // Have a medical examination, book a flight, and prepare for your trip
        arriving();         / / in
    }

    public void applyForPassport(a) {
        System.out.println("3. Handling passport, exit card and notarization for private travel abroad:");
        System.out.println("1) Apply for a private passport and exit card to the local public security organ with the admission notice, household booklet or ID card.");
        System.out.println("2) Handle notarization of birth certificate, diploma, degree and achievement notarization, experience certificate, family relationship notarization, economic guarantee notarization.");
    }

    public void applyForVisa(a) {
        System.out.println(4. Applying for a Visa:);
        System.out.println("1) Prepare all kinds of information required by the application for a foreign entry visa, including proof of personal education background, transcript and work experience; Proof of personal and family income, funds and property; Proof of the relationship of family members, etc.");
        System.out.println("2) Apply for an entry visa to the embassy (consulate) of the country you intend to study in China. When applying, you need to fill in the relevant forms, submit the necessary supporting documents and pay the visa. Some countries (e.g. Us, UK, Canada, etc.) require applicants to visit an embassy for an interview when applying for a visa.);
    }

    public void readyGoAbroad(a) {
        System.out.println(V. Physical examination, Ticket Booking, packing:);
        System.out.println("1) Medical examination, immunization and vaccination against infectious diseases;");
        System.out.println("2) Confirm ticket times, flights and connecting points.");
    }

    // For school information
    public abstract void lookingForSchool(a);

    // Application for admission
    public abstract void applyForEnrol(a);

    / / in
    public abstract void arriving(a);
}
Copy the code

Step 2: Define a specific subclass: Study in the United States

class StudyInAmerica extends StudyAbroad {
    
    @Override
    public void lookingForSchool(a) {
        System.out.println("I. Obtain the following information from the school:");
        System.out.println("1) Have a comprehensive understanding of the political, economic and cultural background, educational system and academic level of the intended country;);
        System.out.println("2) To have a comprehensive knowledge of foreign universities, including history, tuition fees, length of schooling, majors, faculty, teaching facilities, academic status, number of students, etc.");
        System.out.println("3) Find out about the accommodation, transportation and medical insurance of the school;");
        System.out.println("4) Does the school have an overseas study agency authorized to recruit students in China?");
        System.out.println("5) Master the status of student visa;);
        System.out.println("6) Does the government of this country allow international students to work legally?");
        System.out.println("8) Can I emigrate after graduation?");
        System.out.println("9) Is the diploma recognized by China?");
    }

    @Override
    public void applyForEnrol(a) {
        System.out.println("Ii. Admission Application:");
        System.out.println("1) Fill in the registration form;");
        System.out.println("2) Send the application form, personal academic certificate, recent academic transcript, recommendation letter, curriculum vitae, TOEFL or IELTS language test transcript and other information to the school you are applying for;);
        System.out.println("3) In order to leave plenty of time for visa processing, it is recommended to apply as early as possible, generally one year in advance is more leisurely.");
    }

    @Override
    public void arriving(a) {
        System.out.println("Vi. Arrival at target School:");
        System.out.println("1) Arrange accommodation;");
        System.out.println("2) Get to know the campus and its surroundings."); }}Copy the code

Step 3: Test results

/** ** Template method pattern case * 

* Use template method pattern to implement the study abroad procedure design procedure */

public class TemplateMethodPattern { public static void main(String[] args) { StudyAbroad tm=newStudyInAmerica(); tm.templateMethod(); }}Copy the code

The output

1. Obtain the following school information:1) have a comprehensive understanding of the political, economic and cultural background, educational system and academic level of the intended country;2) have a comprehensive knowledge of foreign universities, including history, tuition fees, length of schooling, majors, faculty, teaching facilities, academic status, number of students, etc.3) find out about the accommodation, transportation and medical insurance of the school;4Does the school have an overseas study agency authorized to recruit students in China?5) Master the visa status;6Does the government of this country allow international students to work legally8) Can I emigrate after graduation?9) Is the diploma recognized in China? Ii. Admission Application:1) fill in the entry form;2) Send the application form, personal academic certificate, recent academic transcript, recommendation letter, curriculum vitae, TOEFL or IELTS language test transcript and other information to the school you are applying for;3In order to leave plenty of time for visa processing, it is recommended to apply as early as possible, generally in advance1Year is more leisurely. Iii. Handling of passport, exit card and notarization for private purposes:1) Apply for a private passport and exit card to the local public security organ with the admission notice, household booklet or id card.2For notarization of birth certificate, diploma, degree and achievement, experience certificate, family relationship notarization, economic guarantee notarization. Iv. Visa Application:1) Prepare all the necessary information for the visa application, including proof of personal education, transcript and work experience; Proof of personal and family income, funds and property; Proof of relationship of family members, etc.;2) apply for an entry visa to the embassy (consulate) of the country you intend to study in China. When applying, you need to fill in the relevant forms, submit the necessary supporting documents and pay the visa. Some countries (such as the United States, The United Kingdom, Canada, etc.) require applicants to go to the consulate for an interview when applying for a visa. V. Physical examination, Air ticket Booking and packing preparation1) medical check-ups, immunization tests and vaccination against infectious diseases;2) Confirm ticket times, flights and connecting points. Vi. Arrival at target School:1) arrange accommodation;2) Get to know the campus and its surroundings.Copy the code

advantages

  1. It encapsulates the immutable and extends the mutable. It encapsulates the algorithm which is considered to be the invariant part into the parent class, and inherits the algorithm of the variable part by the subclass, which is convenient for the subclass to continue to expand.
  2. It extracts common parts of the code in the parent class for easy code reuse.
  3. Some methods are implemented by subclasses, so subclasses can be extended to add functionality in accordance with the open closed principle.

disadvantages

  1. You need to define a subclass for each different implementation, which leads to an increased number of classes, a larger system, and a more abstract design.
  2. Abstract methods in the parent class are implemented by the subclass, and the results of the execution of the subclass affect the results of the parent class, leading to a reverse control structure that makes code more difficult to read.

Application scenarios

  1. Use the Template Method pattern when you want the client to extend only specific steps of the algorithm, not the entire algorithm or its structure.
  2. Use this pattern when you have several classes that contain nearly the same algorithm, but with some slight differences.

Schema extension

In the template method pattern, the basic methods include abstract methods, concrete methods, and hook methods. Properly using hook methods allows subclasses to control the behavior of their parent classes. In the example below, you can change the result of a run in an abstract parent class by overriding the hook methods HookMethod1() and HookMethod2() in a concrete subclass, as shown below: The following code:

package com.niuh.designpattern.templatemethod.v3;

/** * Template method mode with hook methods */
public class HookTemplateMethod {
    public static void main(String[] args) {
        HookAbstractClass tm = newHookConcreteClass(); tm.TemplateMethod(); }}// An abstract class with hook methods
abstract class HookAbstractClass {
    // Template method
    public void TemplateMethod(a) {
        abstractMethod1();
        HookMethod1();
        if (HookMethod2()) {
            SpecificMethod();
        }
        abstractMethod2();
    }

    // Specific methods
    public void SpecificMethod(a) {
        System.out.println("A concrete method in an abstract class is called...");
    }

    // Hook method 1
    public void HookMethod1(a) {}// Hook method 2
    public boolean HookMethod2(a) {
        return true;
    }

    public abstract void abstractMethod1(a); // Abstract method 1

    public abstract void abstractMethod2(a); // Abstract method 2
}

// Contains a concrete subclass of the hook method
class HookConcreteClass extends HookAbstractClass {
    public void abstractMethod1(a) {
        System.out.println("The implementation of abstract method 1 is called...");
    }

    public void abstractMethod2(a) {
        System.out.println("The implementation of abstract method 2 is called...");
    }

    public void HookMethod1(a) {
        System.out.println("Hook method 1 overridden...");
    }

    public boolean HookMethod2(a) {
        return false; }}Copy the code

The following output is displayed:

Abstract methods1The implementation is called... Hook method1Be rewritten... Abstract methods2The implementation is called...Copy the code

Application in source code

#Servlet Api
javax.servlet.http.HttpServlet

#Spring
org.springframework.web.servlet.mvc.AbstractController
......
Copy the code

Application of template method pattern in Servlets

In addition to being configured in web.xml, the Servle inherits an abstract class called HttpServlet. The HttpService class provides a service() method that calls one or more of the seven DO methods in response to the client call. These DO methods need to be provided by concrete subclasses of HttpServlet, so this is a typical template method pattern. Here is the source code for the service() method:

protected void service(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
	
    String method = req.getMethod();
	if (method.equals(METHOD_GET)) {
        long lastModified = getLastModified(req);
    	if (lastModified == -1) {
        	// servlet doesn't support if-modified-since, no reason
            // to go through further expensive logic
            doGet(req, resp);
        } else {
        	long ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
            if (ifModifiedSince < (lastModified / 1000 * 1000)) {
            	// If the servlet mod time is later, call doGet()
                // Round down to the nearest second for a proper compare
                // A ifModifiedSince of -1 will always be less
                maybeSetLastModified(resp, lastModified);
                doGet(req, resp);
            } else{ resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); }}}else if (method.equals(METHOD_HEAD)) {
        long lastModified = getLastModified(req);
    	maybeSetLastModified(resp, lastModified);
        doHead(req, resp);

    } else if (method.equals(METHOD_POST)) {
        doPost(req, resp);
            
    } else if (method.equals(METHOD_PUT)) {
        doPut(req, resp);        
            
    } else if (method.equals(METHOD_DELETE)) {
        doDelete(req, resp);
            
    } else if (method.equals(METHOD_OPTIONS)) {
        doOptions(req,resp);
            
    } else if (method.equals(METHOD_TRACE)) {
        doTrace(req,resp);
            
    } else {
        // Note that this means NO servlet supports whatever
        // method was requested, anywhere on this server.

        String errMsg = lStrings.getString("http.method_not_implemented");
        Object[] errArgs = new Object[1];
        errArgs[0] = method; errMsg = MessageFormat.format(errMsg, errArgs); resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg); }}Copy the code

The service() method can also be replaced by subclasses. Here is a simple Servlet example:As you can see from the class diagram above, TestServlet is a subclass of HttpServlet and replaces two methods of the parent class:doGet()anddoPost().

public class TestServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        System.out.println("using the GET method");

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            
        System.out.println("using the POST method"); }}Copy the code

You can see from the example above that this is a typical template method pattern.

  • Httpservlets act as abstract templates
    • Template methods: this is done by the service() method.
    • Basic method: doPost(), doGet() and other methods.
  • TestServlet acts as a concrete template
    • TestServlet replaces two of the seven base methods in the parent HttpServlet class, doGet() and doPost().

PS: The above code is submitted to Github: github.com/Niuh-Study/…

GitHub Org_Hejianhui /JavaStudy GitHub Hejianhui /JavaStudy