Template Method Design Mode Theory and Application

This article is included in github and gitee , with my complete Java series of articles, you can read them for both study and interview

(1) What is Template method

First learn what a template is. When you specify a tool in a factory, you first design a template, and then make tools of various colors from it.Although the tools may be made in different styles and colors, the basic look and pattern are identical.

In programming, we design an abstract class template, specifying the execution process of the code, and subsequent subclasses implement their own code logic, but the execution process is the same as the abstract parent class, which is the template method mode.

(2) Role in Template Method Model

abstractClass:abstract class

The abstract class role is the template mentioned above, where abstract methods and method execution processes are defined and implemented by concreteClass concrete classes

concreteClass: Specific class

Specific classes need to inherit abstract classes and implement abstract methods within them, which will be called in the execution process.

(3) Code cases

Next, you'll show a code case for Template method.In this code, I'll start by writing an abstract class that is the three main steps to open the refrigerator for storage.Next, write two specific classes, one for fruit and one for zooming in.

First, the abstract class: AbstractRefrigerator

public abstract class AbstractRefrigerator {
    public abstract void openDoor();
    public abstract void putSomething();
    public abstract void closeDoor();
    public final void execute(){
        openDoor();
        putSomething();
        closeDoor();
    }
}

In the abstract class, three abstract methods are defined: opening the refrigerator door, putting something in it, and closing the door.Next, define an execute template method that specifies the template's method execution process.
Create the first concrete class, PutFruit:

public class PutFruit extends AbstractRefrigerator {
    private String fruitName;
    public PutFruit(String fruitName){
        this.fruitName=fruitName;
    }
    @Override
    public void openDoor() {
        System.out.println("Open the refrigerator door");
    }
    @Override
    public void putSomething() {
        System.out.println("Put in"+fruitName);
    }
    @Override
    public void closeDoor() {
        System.out.println("Close the refrigerator door");
    }
}

In the first concrete class, a unified abstract class is inherited and three abstract methods are implemented.
Create a second concrete class: PutElephant:

public class PutElephant extends AbstractRefrigerator {
    @Override
    public void openDoor() {
        System.out.println("Open the refrigerator door");
    }
    @Override
    public void putSomething() {
        System.out.println("Put an elephant in");
    }
    @Override
    public void closeDoor() {
        System.out.println("Close the refrigerator door");
    }
}

Finally, two specific classes are used in the main method:

public class Main {
    public static void main(String[] args) {
        AbstractRefrigerator a1=new PutFruit("apple");
        a1.execute();
        AbstractRefrigerator a2=new PutElephant();
        a2.execute();
    }
}

Each of these specific classes has its own implementation, but the final execution process follows the template rules specified in the abstract class, which is the template method design pattern.

(4) Application in Project

I flipped through the projects I've written and those I've written at work and found that there is a project where template design is cleverly used.Because it's a project at work, I won't post code to tell you about the scenario:

This project relies on ES for data query collection, and then returns after doing some processing on the data.There is a well-defined process for templates: Pre-query parameter checking->ES query->post-query result processing->encapsulating result returns.

The set of processes here is made into an abstract class that gives the default pair implementation and provides a template method for performing the above steps in sequence.New interface requirements follow this template process directly.

(5) Application of template method mode in source code

The implementation of the javax.servlet.http.HttpServlet class uses the template method pattern.In HttpServlet, doGet, doHead, doPost, doPut, doDelete, doOptions, doTrace, etc. are defined, and service is a template method:

public abstract class HttpServlet extends GenericServlet {

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //...
    }

    protected void doHead(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //...
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //...
    }

    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //...
    }

    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //...
    }

    protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //...
    }

    protected void doTrace(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //...
    }

    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getMethod();
        long lastModified;
        if (method.equals("GET")) {
            lastModified = this.getLastModified(req);
            if (lastModified == -1L) {
                this.doGet(req, resp);
            } else {
                long ifModifiedSince;
                try {
                    ifModifiedSince = req.getDateHeader("If-Modified-Since");
                } catch (IllegalArgumentException var9) {
                    ifModifiedSince = -1L;
                }

                if (ifModifiedSince < lastModified / 1000L * 1000L) {
                    this.maybeSetLastModified(resp, lastModified);
                    this.doGet(req, resp);
                } else {
                    resp.setStatus(304);
                }
            }
        } else if (method.equals("HEAD")) {
            lastModified = this.getLastModified(req);
            this.maybeSetLastModified(resp, lastModified);
            this.doHead(req, resp);
        } else if (method.equals("POST")) {
            this.doPost(req, resp);
        } else if (method.equals("PUT")) {
            this.doPut(req, resp);
        } else if (method.equals("DELETE")) {
            this.doDelete(req, resp);
        } else if (method.equals("OPTIONS")) {
            this.doOptions(req, resp);
        } else if (method.equals("TRACE")) {
            this.doTrace(req, resp);
        } else {
            String errMsg = lStrings.getString("http.method_not_implemented");
            Object[] errArgs = new Object[]{method};
            errMsg = MessageFormat.format(errMsg, errArgs);
            resp.sendError(501, errMsg);
        }

    }
   
}

(6) Summary

Template method design patterns help us understand what abstract classes mean in programming. Many people know what they are, but they don't understand why they should be used.The template method design model is a good example.

Keywords: Java Design Pattern Interview

Added by YourNameHere on Fri, 03 Sep 2021 09:12:17 +0300