Of the 23 design patterns: template method design pattern

One of 23 Design Patterns: Template Method Design Pattern

One copy per blog

Youth, youth! No matter what kind of setbacks and blows you suffer, you must grit your teeth and hold on, because you have every chance to rebuild your life; as long as you are not discouraged, every setback is just a common stumbling block to a new realm, and will never set you back. People die.
Yesterday was very hard, today is cruel, tomorrow will be beautiful, most people will not survive tomorrow.
Fate comes and goes freely determines the number, contentment and happiness are blessings.
Just think so, you should also go back to life! You have given too little in twenty-seven years to deserve such a gift from life.
No amount of pain can disrupt the rhythm of daily life-this is why he is so strong and waiting for me.
There will always be a day when the water in the Yellow River is clear, and people cannot be poor for a lifetime!
Ordinary world, simple people, small hearts, but endless love for life.
Only labor can make a person strong in life. No matter who you are, you must ultimately admire those laborers who can create life with their hands.
Living in this world, having someone love you is not always a bad thing.
Fate is always not what people want. But it is often in the midst of countless pains, contradictions and hardships that people mature.
                                           ------ "Ordinary World" Lu Yao

@[toc]

1. 23 Design Patterns: Template Method Overview

Design Pattern, or Design Patterns, refers to a code design experience that is used repeatedly in software design. The purpose of using design patterns is to reusable code, improve code scalability and maintainability.

The term design pattern was summarized and extracted by four people Erich Gamma, Richard Helm, Raplh Johnson and Jonhn Vlissides in the 1990s, and wrote a book Design Patterns. The four are also known as the Gang of Four (GoF).

Why use design patterns? The fundamental reason is that in order to achieve maintainability and scalability in software development, it is necessary to reuse code as much as possible and reduce the coupling of code. The design pattern is mainly refined based on OOP programming, and it is based on the following principles:

1.2 Principle of opening and closing

The Open Closed Principle proposed by Bertrand Meyer means that software should be open for extension and closed for modification. The meaning here is that when adding new functions, try not to change the code without changing the code. If the new function is completed by only adding code, that is the best.

1.3 Liskov Substitution Principle

The Liskov substitution principle was proposed by Barbara Liskov, which is an object-oriented design principle, that is, if we call a method of a parent class successfully, then it should be fully operational to replace it with a subclass call.

Design patterns extract some commonly used design ideas into patterns one by one, and then name each pattern, which makes it easier to communicate when using it. GoF divides 23 commonly used patterns into three categories: creational patterns, structural patterns, and behavioral patterns, which we will explain one by one later.

The key to learning design patterns is to learn design ideas. You can’t simply copy them mechanically, and you can’t over-design for the use of design patterns. You must reasonably balance the complexity and flexibility of design, and realize that design patterns are not a panacea.

What are Design Patterns?

Simply put, a design pattern is: a fixed solution to a problem, (can be reused)

There are 23 common design patterns, and the design pattern is called GOF design pattern: for example: here we briefly list some design patterns: singleton pattern, proxy pattern, factory pattern, adapter pattern, Template Method Pattern, Facade Design Pattern, Chain of Responsibility Design Pattern, Observer Pattern….

There is also a common design pattern: called JavaEE design pattern: For example: DAO, DTO, VO, PO, POJO…etc, I won’t go into details here.

1.4 What is the template method design pattern

Template Method (Template Method) is a relatively simple pattern. Its main idea is to define a series of steps for an operation. For some steps that cannot be determined temporarily, leave it to subclasses to implement, so that different subclasses can define different steps.

The core idea of the template method is: the parent class defines the skeleton, and the subclass implements some details.

In order to prevent the subclass from overriding the skeleton method of the parent class, you can use final for the skeleton method in the parent class. For abstract methods that need to be implemented by subclasses, they are generally declared as protected, making these methods invisible to external clients.

From the literal meaning of the template method design pattern, we can know that the most important and important one is the template method. For the template method design pattern, setting a reasonable template method is the core. After the template method is designed, the design of the template method design pattern is basically completed.

Generally speaking, template methods exist in template classes, and template classes are usually abstract classes. Because the method we delay the rewriting of this subclass is an abstract method, and abstract methods can only be defined in abstract classes and interfaces, but methods cannot be defined in interfaces (and interfaces are generally used to define specifications)

Define the core algorithm skeleton in the template method of the template class, and the specific implementation steps can be delayed to the subclass. Generally, the core algorithm is modified by the final keyword (it cannot be overwritten, but it may not be final). On the one hand, it is protected and cannot be changed. On the other hand, That is, the algorithm is reused. On the other hand, the code is also reused, because the code of some steps in the algorithm is fixed, and this fixed code will not change with the change of the subclass, and this part of the code can be written into the template.

And the method that we delay until the subclass handles the implementation is defined as an abstract method. This method that is not sure about the implementation, how to deal with it, how to implement it, etc., is left to the subclass to do (rewrite the abstract method).

2. Example of template method design pattern

Below we will demonstrate the processing of the same transaction, respectively using the template method design pattern processing, and processing without the template method design pattern, comparing the quality of the two processing.

Here we simply deal with one: a day’s business description for students and teachers.

2.1 Handling of design patterns without template method

The following is the code design of the Student student class

package com.RainbowSea.templateMethod;

public class Student {<!-- -->

    public void day() {<!-- -->
        getUp();
        brushTeeth();
        eatFast();
        doSome();
    }

    public void getUp() {<!-- -->
        System.out.println("Get up");
    }

    public void brushTeeth() {<!-- -->
        System.out.println("Brush teeth");
    }

    public void eatFast() {<!-- -->
        System.out.println("have breakfast");
    }


    public void doSome() {<!-- -->
        System.out.println("Student, studying in class");
    }
}

The following is the code design of the Teacher class

package com.RainbowSea.templateMethod;

public class Teacher {<!-- -->

    public void day() {<!-- -->
        getUp();
        brushTeeth();
        eatFast();
        doSome();
    }

    public void getUp() {<!-- -->
        System.out.println("Get up");
    }

    public void brushTeeth() {<!-- -->
        System.out.println("Brush teeth");
    }

    public void eatFast() {<!-- -->
        System.out.println("have breakfast");
    }


    public void doSome() {<!-- -->
        System.out.println("teacher, teaching");
    }
}

The following is the code design of Test running test

package com.RainbowSea.templateMethod;

public class Test {<!-- -->
    public static void main(String[] args) {<!-- -->
        Student student = new Student();
        student. day();
        System.out.println("********************************");

        Teacher teacher = new Teacher();
        teacher. day();

    }
}
 

The above demonstration is the result of the thought processing without using the template method design pattern:

From it, we can see that the code design of the two Teacher classes and the Student class is only the doSome() method is different, and the other methods have the same processing results, so we can repeat the The same code is integrated to improve code reusability and reduce code redundancy. As follows, we use the template method to design pattern processing.

2.2 Processing of Design Patterns Using Template Method

From the above design pattern processing without using the template method, there is a lot of code redundancy, and the code reusability is extremely poor. From the analysis of the above results, we can know: the code design of the Teacher class and the Student class is only the doSome() method is different, and the other methods have the same processing results. So here is the design pattern of our template method: Set the day() method as the core algorithm skeleton of the template method, and the uncertain processing method of the doSome() method is delayed to the inherited child The class is implemented concretely, and all the methods in it are defined in the template class. This template class is generally an abstract class, and here we define it as the Person abstract class. The specific code is implemented as follows:

The following is the design code of the Person template class

package com.RainbowSea.templateMethod;


/**
 * Both Teacher and Student are Person
 * 1. Person is the template class in the template method design pattern
 * 2. The day() method is the template method in the template method design pattern.
 * A template class is usually an abstract class. The template method in the template class defines the core algorithm. This method is usually final (but it may not be final)
 * The abstract method in the template class is a method that is not sure how to implement it. This thing that is not sure how to implement is left to the subclass.
 *
 *
 */
public abstract class Person {<!-- --> // Template classes are usually abstract classes
        /**
         * This method describes a student's day
         */
        // After adding final, this method cannot be overridden, so the core algorithm can also be protected.
        // template method:
        // The template method defines the core algorithm skeleton: the specific implementation steps can be delayed to subclasses.
        // On the one hand, the core algorithm is protected and cannot be changed; on the other hand, the algorithm is reused.
        // In addition, the code is also reused, because the code of some steps in the algorithm is fixed, and this fixed code will not follow the subclass
        // changes, this part of the code can be written into the template,
        public final void day() {<!-- -->
            getUp();
            brushTeeth();
            eatFast();
            doSome();
        }

        // Some of the steps: will not change with the change of the subclass, these codes can be written into the parent class, and the code can be reused.
        public void getUp() {<!-- -->
            System.out.println("Get up");
        }

        public void brushTeeth() {<!-- -->
            System.out.println("Brush teeth");
        }

        public void eatFast() {<!-- -->
            System.out.println("have breakfast");
        }


        // This step is to be done, but how to do this step is up to the subclass.
        public abstract void doSome(); // defined as an abstract method
}

Code design of the Student class

package com.RainbowSea.templateMethod;

public class Student extends Person{<!-- -->
    @Override
    public void doSome() {<!-- -->
        System.out.println("Student, studying in class");
    }
}

Teacher class code design

package com.RainbowSea.templateMethod;

public class Teacher extends Person{<!-- -->
    @Override
    public void doSome() {<!-- -->
        System.out.println("teacher teaching,");
    }
}

Test runs tests

package com.RainbowSea.templateMethod;

public class Test {<!-- -->
    public static void main(String[] args) {<!-- -->
        Person p1 = new Teacher();
        p1. day();

        System.out.println("******************");
        Person p2 = new Student();
        p2. day();

    }
}

3. Summary:

  1. Design pattern: a fixed solution to a problem, (can be reused)

  2. Template Method (Template Method) is a relatively simple pattern. Its main idea is to define a series of steps for an operation. For some steps that cannot be determined temporarily, leave it to subclasses to implement, so that different subclasses can define different steps.

  3. The core idea of the template method is: the parent class defines the skeleton, and the subclass implements some details.

  4. In order to prevent the subclass from overriding the skeleton method of the parent class, you can use final for the skeleton method in the parent class. For abstract methods that need to be implemented by subclasses, they are generally declared as protected, making these methods invisible to external clients.

  5. Learn design patterns well, submit your code reusability, and make your code more elegant.

4. Finally

It is limited to my own level, and there are mistakes in it. I hope everyone can give me advice. Han Xin will order troops-the more the better, thank you everyone, there will be a period later, see you in the world! ! !