Design pattern---Template Method pattern

1 Definition

The template method pattern defines an algorithm framework in the parent class, and the specific steps can be delayed to the subclass to implement, so that the subclass can redefine some specific steps of the algorithm without changing the algorithm framework.

2 Structure diagram

The main roles are explained below

Abstract class/abstract template (Abstract Class)

Abstract template class responsible for giving the outline and skeleton of an algorithm. It consists of a template method and several basic methods. The definitions of these methods are as follows.

① Template method: defines the skeleton of the algorithm and calls the basic methods it contains in a certain order.

② Basic method: It is a step in the whole algorithm, including the following types.

  • Abstract method: declared in an abstract class and implemented by a concrete subclass.
  • Concrete method: It has been implemented in the abstract class and can be inherited or overridden in the concrete subclass.
  • Hook method: It has been implemented in the abstract class, including logical methods for judgment and empty methods that need to be rewritten by subclasses.

Concrete subclass/concrete implementation (Concrete Class)

The concrete implementation class implements the abstract methods and hook methods defined in the abstract class, which are a constituent step of a top-level logic.

3 Advantages and disadvantages

3.1 Advantages

1. It encapsulates the invariant part and extends the variable part. It encapsulates the algorithm that is considered to be the invariant part into the parent class, and implements the variable part algorithm by inheritance from the subclass, so that the subclass can continue to expand.

2. It extracts the common part of the code in the parent class, which is convenient for code reuse.

3. Some methods are implemented by subclasses, so subclasses can add corresponding functions by extension, which conforms to the open-closed principle.

3.2 Disadvantages

1. A subclass needs to be defined for each different implementation, which will lead to an increase in the number of classes, a larger system, and a more abstract design, which indirectly increases the complexity of the system implementation.

2. The abstract method in the parent class is implemented by the child class, and the result of the execution of the child class will affect the result of the parent class, which leads to a reverse control structure, which increases the difficulty of code reading.

3. Due to the shortcomings of the inheritance relationship itself, if the parent class adds a new abstract method, all subclasses must be changed again.

4 Code Examples

For example, a student goes to eat after school. Everyone walks to the cafeteria and goes to the cafeteria to cook different dishes. After eating, there will be different actions. Classmate A goes back to the dormitory to sleep, and classmate B goes back to the classroom to continue studying.

4.1 Abstract class MyDinner

/**
 * @program: design-pattern-learning
 * @author: zgr
 * @create: 2021-09-23 10:52
 **/
public abstract class MyDinner {

    public void templateMethod(){

        printStudentIdentity();
        /**
         * 下课一起去食堂吃饭,大家走去食堂方式一样,去食堂打的饭菜不一样,吃完饭回的地方不一样,有人回宿舍,有人回教室
         */

        walk();

        haveMeal();

        goAfterMeal();
    }

    /**
     * 打印学生身份
     */
    public abstract void printStudentIdentity();

    public void walk(){
        System.out.println("到点了,走去吃晚饭");
    }

    /**
     * 打饭,具体打什么菜
     */
    public abstract void haveMeal();

    /**
     * 吃完饭后去哪儿
     */
    public abstract void goAfterMeal();
}

4.2 Student A StudentA

/**
 * @program: design-pattern-learning
 * @author: zgr
 * @create: 2021-09-23 11:01
 **/
public class StudentA extends MyDinner{

    @Override
    public void printStudentIdentity(){
        System.out.println("我是学生A");
    }

    @Override
    public void haveMeal() {
        System.out.println("今天心情不错,来一个麻辣香锅,重麻重辣");
    }

    @Override
    public void goAfterMeal() {
        System.out.println("吃饱喝足,回宿舍再睡一觉,简直美吱吱");
    }
}

4.3 Student B StudentB

/**
 * @program: design-pattern-learning
 * @author: zgr
 * @create: 2021-09-23 11:03
 **/
public class StudentB extends MyDinner{

    @Override
    public void printStudentIdentity(){
        System.out.println("我是学生B");
    }

    @Override
    public void haveMeal() {
        System.out.println("考试没考好,就吃个最便宜的拉面吧");
    }

    @Override
    public void goAfterMeal() {
        System.out.println("接着去自习室吧,我需要好好复习了");
    }
}

4.4 Main function MainClass

/**
 * @program: design-pattern-learning
 * @author: zgr
 * @create: 2021-09-23 10:51
 **/
public class MainClass {

    public static void main(String[] args) {
        MyDinner studentA = new StudentA();
        studentA.templateMethod();

        System.out.println("**********************************");

        MyDinner studentB = new StudentB();
        studentB.templateMethod();
    }

}

 4.5 Running Results

5 Application scenarios of template method pattern

1. The overall steps of the algorithm are very fixed, but when individual parts are variable, the template method pattern can be used at this time to abstract the easily variable parts for subclasses to implement.

2. When multiple subclasses have common behaviors, they can be extracted and concentrated into a common parent class to avoid code duplication. First, identify differences in existing code and separate them into new operations. Finally, replace the different code with a template method that calls these new operations.

3. When it is necessary to control the extension of the subclass, the template method only calls the hook operation at specific points, so that the extension is only allowed at these points.

6 Quotes

1. "Dahua Design Patterns"

2. Detailed explanation of template method pattern (template method design pattern)

7 Source code

design-pattern-learning/src/com/hz/design/pattern/template/method at main · airhonor/design-pattern-learning · GitHub

Guess you like

Origin blog.csdn.net/honor_zhang/article/details/120431774