16, Template method pattern

Keywords: Java Design Pattern

0. Ma Xian inspirational

Loneliness does not give others the opportunity to pity you, but gives you the opportunity to find yourself stronger.

1. General

In the process of object-oriented programming, programmers often encounter this situation: when designing a system, they know the key steps required by the algorithm and determine the execution order of these steps, but the specific implementation of some steps is still unknown, or the implementation of some steps is related to the specific environment.

For example, when you go to a bank to handle business, you generally go through the following four processes: number retrieval, queuing, handling specific business, scoring bank staff, etc. the businesses of number retrieval, queuing and scoring bank staff are the same for each customer and can be implemented in the parent class, but the specific business varies from person to person. It may be deposit, withdrawal or transfer, Implementation can be deferred to subclasses.

definition:

Define the algorithm skeleton in an operation, and delay some steps of the algorithm to the subclass, so that the subclass can redefine some specific steps of the algorithm without changing the structure of the algorithm.

2. Structure

The Template Method pattern contains the following main roles:

  • Abstract Class: it is responsible for giving the outline and skeleton of an algorithm. It consists of a template method and several basic methods.

    • Template method: defines the skeleton of the algorithm and calls its basic methods in a certain order.

    • Basic method: it is the method to realize each step of the algorithm and an integral part of the template method. The basic methods can be divided into three types:

      • Abstract method: an abstract method is declared by an abstract class and implemented by its concrete subclasses.

      • Concrete method: a concrete method is declared and implemented by an abstract class or concrete class, and its subclasses can be overridden or inherited directly.

      • Hook method: it has been implemented in abstract classes, including logical methods for judgment and empty methods that need to be overridden by subclasses.

        General hook methods are logical methods used for judgment. The name of such methods is usually isXxx, and the return value type is boolean.

  • Concrete Class: implement the abstract methods and hook methods defined in the abstract class. They are the constituent steps of top-level logic.

3. Case realization

Fried vegetables

The steps of cooking are fixed, which are divided into pouring oil, hot oil, pouring vegetables, pouring spices, stir frying and so on. Now use the template method pattern to simulate with code. Class diagram is as follows:

The code is as follows:

public abstract class AbstractClass {
    
    public final void cookProcess() {
        //Step 1: pour oil
        this.pourOil();
        //Step 2: hot oil
        this.heatOil();
        //Step 3: pour the vegetables
        this.pourVegetable();
        //Step 4: pour the seasoning
        this.pourSauce();
        //Step 5: stir fry
        this.fry();
    }

    public void pourOil() {
        System.out.println("Pour oil");
    }

    //Step 2: the hot oil is the same, so it can be realized directly
    public void heatOil() {
        System.out.println("hot oil");
    }

    //Step 3: pouring vegetables is different (one is cabbage, the other is cabbage)
    public abstract void pourVegetable();

    //Step 4: pouring seasoning is different
    public abstract void pourSauce();


    //Step 5: stir fry is the same, so it can be realized directly
    public void fry(){
        System.out.println("Fry and fry until cooked");
    }
}

public class ConcreteClass_BaoCai extends AbstractClass {

    @Override
    public void pourVegetable() {
        System.out.println("The vegetables in the pot are cabbage");
    }

    @Override
    public void pourSauce() {
        System.out.println("The sauce in the pot is pepper");
    }
}

public class ConcreteClass_CaiXin extends AbstractClass {
    @Override
    public void pourVegetable() {
        System.out.println("The vegetables in the pot are heart vegetables");
    }

    @Override
    public void pourSauce() {
        System.out.println("The sauce is minced garlic");
    }
}

public class Client {
    public static void main(String[] args) {
        //Fried shredded cabbage
        ConcreteClass_BaoCai baoCai = new ConcreteClass_BaoCai();
        baoCai.cookProcess();

        //Stir fried cabbage with minced garlic
        ConcreteClass_CaiXin caiXin = new ConcreteClass_CaiXin();
        caiXin.cookProcess();
    }
}

Note: in order to prevent malicious operations, the general template method adds the final keyword.

4. Advantages and disadvantages

advantage:

  • Improve code reusability

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

  • Reverse control is realized

    Through a parent class calling the operation of its subclasses, different behaviors are extended through the specific implementation of subclasses, which realizes the reverse control and conforms to the "opening and closing principle".

Disadvantages:

  • A subclass needs to be defined for each different implementation, which will increase the number of classes, make the system larger and the design more abstract.
  • Abstract methods in the parent class are implemented by subclasses, and the execution results of subclasses will affect the results of the parent class, which leads to a reverse control structure, which improves the difficulty of code reading.

5. Applicable scenarios

  • The overall steps of the algorithm are very fixed, but when individual parts are changeable, you can use the template method pattern to abstract the easily changeable parts for subclass implementation.
  • It is necessary to determine whether a step in the parent algorithm is executed through the subclass to realize the reverse control of the subclass over the parent.

6.JDK source code analysis

The InputStream class uses the template method pattern. Multiple read() methods are defined in the InputStream class, as follows:

public abstract class InputStream implements Closeable {
    //Abstract method that requires subclasses to be overridden
    public abstract int read() throws IOException;

    public int read(byte b[]) throws IOException {
        return read(b, 0, b.length);
    }

    public int read(byte b[], int off, int len) throws IOException {
        if (b == null) {
            throw new NullPointerException();
        } else if (off < 0 || len < 0 || len > b.length - off) {
            throw new IndexOutOfBoundsException();
        } else if (len == 0) {
            return 0;
        }

        int c = read(); //The parameterless read method is called, which reads one byte of data at a time
        if (c == -1) {
            return -1;
        }
        b[off] = (byte)c;

        int i = 1;
        try {
            for (; i < len ; i++) {
                c = read();
                if (c == -1) {
                    break;
                }
                b[off + i] = (byte)c;
            }
        } catch (IOException ee) {
        }
        return i;
    }
}

As can be seen from the above code, the parameterless read() method is an abstract method, and subclasses must be implemented. The read(byte b []) method calls the read(byte b[], int off, int len) method, so the focus here is on the method with three parameters.

In lines 18 and 27 of this method, you can see that the parameterless Abstract read() method is called.

The summary is as follows: the method of reading a byte array data has been defined in the InputStream parent class. It is to read one byte at a time, store it in the first index position of the array, and read len bytes of data. How to read a byte of data? Implemented by subclasses.

This blog comes from the summary of dark horse programmer's video tutorial and the arrangement of notes. It is only for learning and communication. It should not be used for commercial purposes. If there is infringement, please contact the blogger to delete it. Blogger QQ: 194760901

Posted by Call-911 on Sun, 24 Oct 2021 10:49:50 -0700