Behavioral template approach pattern

1. Definition of template method pattern

An official point: define an algorithm framework in operation, and delay some steps to subclasses, so that subclasses can redefine some specific steps of an algorithm without changing the structure of an algorithm.

More popular: it abstracts some common operations (Methods) and encapsulates them in a template method, which can override the relevant methods in its subclasses.

Take chestnuts for example:

 

Just like making tea in life, some steps are the same. For example, the first step is to boil water, the second step is to add tea, the third step is to record the time, and the fourth step is whether to put medlar ~. The methods in the above steps can be encapsulated after being abstracted, and subclasses can be rewritten after inheritance. The tea brewing jasmine tea class will be rewritten, and the tea brewing Longjing tea class will be rewritten, and the tea brewing method will be rewritten, and the tea brewing Longjing tea class will be rewritten, and the tea brewing method will be rewritten, and so on...

2. Write a small case

Write a small demo according to the above scenario

First, create a new tea making abstract class, which defines a template method of tea making steps and the abstract methods of each step.

/**
 * @author lw
 * @Title:
 * @Description:Template method abstract class
 * @Version 1.0
 */
public abstract class AbstractMakeTeaTemplate {

    /**
     * @Author lw
     * @Description //TODO Template method. The template method must be decorated with final to prevent it from being rewritten
     * @Param []
     * @return void
     **/
    public final void makeTeaTemplateMethod(){
        //Boil water
        boilWater();
        //Put tea
        putTea();
        //Write down the start time
        recordBeginTime();
        //Write down the end time
        recordEndTime();
        //Put medlar (here is the hook function, which is put Medlar by default. If you don't want to put medlar, you can override the method return false in the derived class)
        if(isAddChineseWolfberry()){
            System.out.println("Add a handful of medlar!~~~~~");
        }
    }
    //Water boiling method
    public abstract void boilWater();

    //Put tea into the water
    public abstract void putTea();

    //Record the tea making time
    public void recordBeginTime(){
        System.out.println("Time to start making tea:"+System.currentTimeMillis());
    }
    //Record the tea making time
    public void recordEndTime(){
        System.out.println("End tea making time:"+System.currentTimeMillis());
    }

    //Add medlar
    public boolean isAddChineseWolfberry(){
        return true;
    };

}

Note: 1 Template methods must be decorated with final to prevent them from being overridden in derived classes. 2. You can define some hook functions to determine whether to execute a step in the template method by rewriting (just like whether to add medlar in the abstract class, it is added by default. You can override return false in the subclass, so you don't need to add ~ ~).

 

Create a new jasmine tea brewing class and inherit the AbstractMakeTeaTemplate abstract class

/**
 * @author lw
 * @Title:
 * @Description:Make a cup of jasmine tea
 * @Version 1.0
 */
public class MakeJasmineTea extends AbstractMakeTeaTemplate{
    @Override
    public void boilWater() {
        System.out.println("There is a mine at home, burning a pot, and the farmer's three fists...");
    }

    @Override
    public void putTea() {
        System.out.println("Add a thousand dollars or two of jasmine tea...");
    }

}

Create a new paolongjing tea class and inherit the AbstractMakeTeaTemplate abstract class

/**
 * @author lw
 * @Title:
 * @Description:Make a cup of Longjing tea
 * @Version 1.0
 */
public class MakeLongJingTea extends AbstractMakeTeaTemplate{
    @Override
    public void boilWater() {
        System.out.println("The family is poor. Burn a pot of tap water~~");
    }

    @Override
    public void putTea() {
        System.out.println("Put five yuan and three bags of expired Longjing tea....");
    }

    /**
     * @Author lw
     * @Description //TODO Because there is no money, no medlar is added. return false here to override the isAddChineseWolfberry method of the parent class
     * @Param []
     * @return boolean
     **/
    public boolean isAddChineseWolfberry(){
        return false;
    };
}

Note: this class overrides the method of whether to add Lycium barbarum. return false. It does not need to be executed in the template method

System.out.println("add a handful of Lycium barbarum for tonic! ~ ~ ~); That's the code

This hook can be handled flexibly according to the actual situation.

Execute it in the main method,

public class TemplateMethodMainTest {
    public static void main(String[] args) {
        AbstractMakeTeaTemplate amtt = new MakeJasmineTea();
        amtt.makeTeaTemplateMethod();
        System.out.println("--------------");
        AbstractMakeTeaTemplate amtt1 = new MakeLongJingTea();
        amtt1.makeTeaTemplateMethod();
    }
}

Look at the results

 3. Advantages and disadvantages of template method pattern

Advantages: 1. Package the unchanged part and expand the variable part. 2. Extract common codes for easy maintenance. 3. The behavior is controlled by the parent class and implemented by the child class.

Disadvantages: each different implementation requires a subclass to implement, resulting in an increase in the number of classes and a larger system.

4. Outside the picture ~

As a programmer who likes to drink tea, Amway is a good place to go. Chashan village, Yu County, Zhangjiakou City, Hebei Province, is a place for self driving and camping. I went there once two years ago. The scenery is great. I really feel integrated into nature. The mountains are good and the water is good. When I came back, I filled a few barrels of mountain spring water to make tea. There is no residue at all. Colleagues who work hard in Beijing / like outdoor can experience it! (PS: wear warm equipment. Children's shoes with poor driving skills are not recommended to go alone. It's difficult to walk on alpine meadow road ~ ~)

 

 

 

 

 

Keywords: Java Design Pattern

Added by phphelpme on Fri, 17 Dec 2021 20:25:30 +0200