Template mode: Extend your pipeline elegantly and flexibly

Template method, as a behavioral pattern , defines the algorithm skeleton of an operation in an abstract class or interface, and delays the specific execution of some steps to the subclass, so that the method execution of the parent class can be different. result. Thus, the design purposes of code reuse, good scalability and high flexibility are achieved.

When to use

When the template method is used, it is mainly the case where the same and similar methods are used more. Using the template method, these similar methods can be extracted, and a relatively universal template can be formulated, thereby reducing the repetitive writing of code and improving the code reuse rate. The abstract usage scenarios and implementation logic are shown in the following figure.

image-20220327125629386.png

basic definition

Before understanding how to write template methods, it is necessary to understand some key terms and terms related to template methods.

basic method:

The basic methods can be divided into the following three categories:

1. Concrete Method

The specific method refers to the method implemented by the parent class/interface, and the subclass cannot change the method.

2. Abstract Method

​Abstract method means that the specific steps are not implemented by the parent class/interface, but the specific operation steps are postponed to the subclass implementation, so as to achieve different operations for different situations.

3. Hook Method

A hook method is declared and implemented by an abstract class, and subclasses extend it. It is a method that subclasses can selectively implement or not implement . Usually an abstract class is given an empty implementation as the default implementation of the method.

Such a default implementation is called a default hook method . This empty hook method is also called "Do Nothing Hook". The default hook method is also used in the default adaptation mode. The default adaptation pattern is that a class provides a default empty implementation of the interface, so that subclasses do not have to provide implementations of all methods, because usually a concrete class does not need all methods. This idea coincides with the default hook method.

​ 钩子方法常见的用途为,将两个存在不同调用关系的pipeLine流程,通过钩子方法联系到同一个模版中,从而屏蔽不同内容的差异性。但是,需要注意的一点是,**钩子方法的名字应当以do开始,这是熟悉设计模式的Java开发人员的标准做法。**如doScan、doGet等。

模版方法:

​ 模版方法是模版模式的核心点,其是定义在抽象类中的,是把基本操作方法组合在一起形成总的算法或行为的方法。一个抽象类可以有任意多个模板方法,而不限于一个。每一个模板方法都可以调用任意多个具体方法。原则上,子类不可以、也不应该对模版方法进行覆盖或者重写

上述定义中各类方法的对应模块大致如下图所示:

image-20220327133826087.png

代码实践

模版方法的实现,在java中有两种方式,一种是基于抽象类的实现方式,另外一种则是基于接口的实现方式

这里我们以抽象类的实现方法为例子介绍相应的模版方法的实现。

public abstract class Template {

    public void concreteMethod() {
        System.out.println("concreteMethod:");
    }

    public abstract void abstractMethod();

    public void hookMethod(){
        System.out.println("hookMethod:");
        System.out.println("实现默认hookMethod!");
    }


    public final void execute() {
        concreteMethod();

        abstractMethod();

        hookMethod();
    }
}
复制代码

首先,定义出我们的模版接口,其中包含三个方法concreteMethod、abstractMethod、hookMethod。就分别对应于我们上述提到的具体方法、抽象方法及钩子方法

然后在execute()方法内,定义好三个方法的基本执行方法,同时采用final修饰符,使得子类无法修改execute方法中的执行顺序。

然后在我们的子类HerFuction中,首先必须要对抽象方法进行相应的实现。这里我们简单的输出类名。

而在钩子方法hookMethod中,我们则对原方法进行增强,多输出一句话:“我还要执行自己的hookMethod方法!”。

public class HerFunction implements Template {

    @Override
    public void abstractMethod() {
        System.out.println("HerFunciton !");
    }

    @Override
    public void hookMethod() {
        Template.super.hookMethod();
        System.out.println("我还要执行自己的hookMethod方法!");
    }
}
复制代码

Similarly, in the second subclass MyFunction, we also need to implement the corresponding abstract class method. But for the hook method, the method in the default abstract class can be used.

public class MyFunction extends Template {

    @Override
    public void abstractMethod() {
        System.out.println("My Function!");
    }
}
复制代码

Finally, create objects corresponding to MyFunction and HerFunction respectively in the startup method, and call the execute method of the parent class.

    public static void main(String[] args) {
        Template myFunction = new MyFunction();
        myFunction.execute();
        System.out.println("================我是分割线=========================");
        Template herFunction = new HerFunction();
        herFunction.execute();
    }
复制代码

The final result is as follows:

image-20220327145635211.png

It can be seen that the subclasses have successfully reused the concreteMethod method, while for the abstractMethod, different logics have been implemented according to different subclasses, reflecting the differences. At the same time, the default implementation and subclass implementation of the hook method also reflect the flexibility of the template.

Analysis of advantages and disadvantages

advantage:

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

2. Put the processing codes of the same business meaning into different subclasses, and add new behaviors by extending the subclasses, thereby improving the expansibility of the code.

3. Write the unchanged behavior on the parent class, remove the duplicate code of the subclass, and provide a good code reuse platform, which conforms to the open-closed principle.

shortcoming:

1. The implementation of the template method depends on the construction of subclasses, so the number of classes will increase significantly, increasing the complexity of the class.

2. In the case of abstract classes, the inheritance relationship itself has certain shortcomings. If the parent class adds a new abstract method, all subclasses must implement the abstract method. The JAVA language can use the interface + default keyword to avoid this modification to a certain extent. (But the side effect is that you cannot use final to limit the method)

references

Template mode (Template) of "JAVA Design Patterns"

Template mode

Explain the essential reasons for introducing the default keyword in the Java8 interface

Advantages and disadvantages of template pattern

Guess you like

Origin juejin.im/post/7079680230104760327