Architect's internal mental skill, detailed explanation of the template model of workflow standardization in the workplace

Posted by Jr0x on Wed, 26 Feb 2020 14:58:28 +0100

Template pattern, also known as Template Method Pattern, refers to defining the skeleton of an algorithm and allowing subclasses to provide implementation for one or more steps. The template method enables the subclass to redefine some steps of the algorithm without changing the structure of the algorithm.

1, Application scenario of template method

The template method is applicable to the following application scenarios:

  • Implement the invariant part of an algorithm at one time, and leave the variable behavior to the subclass for implementation
  • The common behavior in each subclass is extracted and concentrated into a common parent class, so as to avoid code duplication.

The application scenarios of template methods in real life include filling in the enrollment registration form, cooking process, putting elephants in the refrigerator, etc

Take the company's technical training process as an example:

Issue training notice - > make training PPT - > organize employee training - > on-site (remote) training - > submit training questionnaire. Let's create a technical training class:

public abstract class TechnicalTraining {

    protected final void createTraining() {

        /**
         * Issue training notice
         */
        this.PostNotice();
        /**
         * Production training PPT
         */
        this.createPPT();
        /**
         * Organize staff training
         */
        this.OrganizeTraining();

        /**
         * Support distance training if there is one
         */
        if(needOnline()) {
            online();
        }

        /**
         * On site (remote) training
         */

        this.training();
        /**
         * Submit training questionnaire
         */
        this.sumitQuestionnaire();

    }

    final void PostNotice() {
        System.out.println("Issue training notice");
    }

    final void createPPT() {
        System.out.println("Production training PPT");
    }

    final void OrganizeTraining() {
        System.out.println("Organize staff training");
    }

    final void training() {
        System.out.println("On site (remote) training");
    }

    final void sumitQuestionnaire() {
        System.out.println("Submit training questionnaire");
    }

    //Online training
    abstract void online();

    protected boolean needOnline() {
        return false;
    }

}

There is a Boolean value judgment in the above code. This is the hook method used. The main purpose is to intervene the execution process, so that we can control the behavior process more flexibly and meet the requirements of the actual business. The return value of hook method is generally the return value suitable for conditional branch statement (such as boolean, int, etc.). You can decide whether to use the hook method according to your business scenario.

To create a Java training class:

public class JavaTraining extends TechnicalTraining {
    @Override
    void online() {
        System.out.println("Distance training java Related technology");
    }
}

To create a database training class:

public class DatabaseTraining extends TechnicalTraining {

    private boolean needOnlineFlag = false;

    public DatabaseTraining(boolean needOnlineFlag) {
        this.needOnlineFlag = needOnlineFlag;
    }

    @Override
    void online() {
        System.out.println("Related technology of remote training database");
    }

    @Override
    protected boolean needOnline() {
        return this.needOnlineFlag;
    }
}

Test code:

public static void main(String[] args) {

TechnicalTraining javaTraining = new JavaTraining();
javaTraining.createTraining();

TechnicalTraining databaseTraining = new DatabaseTraining(true);
databaseTraining.createTraining();
}

2, The embodiment of template pattern in source code

2.1 AbstractList class

First look at the source code:

/**
 * {@inheritDoc}
 *
 * @throws IndexOutOfBoundsException {@inheritDoc}
 */
abstract public E get(int index);

The get () method is an abstract method, so its logic is to be implemented by subclasses, and ArrayList is the subclass of AbstractList. See the implementation code of get() method in ArrayList:

 /**
 * Returns the element at the specified position in this list.
 *
 * @param  index index of the element to return
 * @return the element at the specified position in this list
 * @throws IndexOutOfBoundsException {@inheritDoc}
 */
public E get(int index) {
    rangeCheck(index);

    return elementData(index);
}

Similarly, if you have AbstractList, you will have AbstractMap and AbstractSet classes.

2.2 HttpServlet class

It's used every day HttpServlet, which inherits from the abstract class GenericServlet, has three methods: service() and init(), destory(), which are all abstract implementations of template methods. Look at the source code:

public abstract class GenericServlet implements Servlet, ServletConfig, Serializable {
    private static final long serialVersionUID = 1L;
    private transient ServletConfig config;

    public GenericServlet() {
    }

    public void destroy() {
    }

    public String getInitParameter(String name) {
        return this.getServletConfig().getInitParameter(name);
    }

    public Enumeration<String> getInitParameterNames() {
        return this.getServletConfig().getInitParameterNames();
    }

    public ServletConfig getServletConfig() {
        return this.config;
    }

    public ServletContext getServletContext() {
        return this.getServletConfig().getServletContext();
    }

    public String getServletInfo() {
        return "";
    }

    public void init(ServletConfig config) throws ServletException {
        this.config = config;
        this.init();
    }

    public void init() throws ServletException {
    }

    public void log(String msg) {
        this.getServletContext().log(this.getServletName() + ": " + msg);
    }

    public void log(String message, Throwable t) {
        this.getServletContext().log(this.getServletName() + ": " + message, t);
    }

    public abstract void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException;

    public String getServletName() {
        return this.config.getServletName();
    }
}

3, Advantages and disadvantages of template method

Advantage:

  • Using template method to put the same processing logic code into abstract parent class can improve the reusability of code;

  • In order to improve the scalability of the code, new behaviors are added to different subclasses of different codes through the extension of subclasses;

  • It provides a good platform for code reuse, which conforms to the principle of opening and closing.

Disadvantages:

  • With the increase of the number of classes, each abstract class needs to be implemented by a subclass, which leads to the increase of the number of classes;
  • The increase of the number of classes indirectly increases the complexity of system implementation;
  • Inheritance relationship has its own shortcomings. If the parent class adds new abstract methods, all the children should be changed.

Topics: Programming Java Database