Java Design Patterns--Template Pattern

1 Template Pattern Template Pattern

Purpose: An abstract class publicly defines the way/template for executing its methods, and its concrete implementation is carried out in the subclass;
Implementation: The key logic is implemented in the abstract class, and other steps are implemented in the subclass.

1. Scenarios of this pattern: 1) division of labor and cooperation, 2) separation of public code and personalized code, etc.;
2. Provide a method called template method in the abstract parent class to define the execution order of these basic methods, and through Its subclasses can cover some steps, so that the same algorithm framework can have different execution results;
3. In order to prevent malicious operations, the general template method is added with the final keyword.

2 Implementation

Code scene: There are many booths for children to color plaster dolls in Lianhu Park.
The plaster sculpture has been done by the boss, but the task of coloring is handed over to the little friends.

2.1 Code Implementation

peppa pig plaster sculpture abstract class

public abstract class AbstractPlasterSculpture {

    public final void show() {
        //生产模型雕塑
        productPlasterSculpture();
        //給模型上色
        coloring();
    }

    public void productPlasterSculpture()
    {  
        System.out.println("找些薄的铁皮来,沿着泥塑的高点把铁片插进去"); 
        System.out.println("把石膏粉或水一遍一遍的洒在泥塑上面"); 
        System.out.println("等干了以后,把在插片处一点一点把几半石膏模分开"); 
        System.out.println("在石膏模具里面加点钢筋,缠上麻丝"); 
        System.out.println("干了以后再用凿子把磨具敲碎,这样一个石膏雕塑出炉了"); 
    }
    //给雕塑上色 子类来实现 不同的儿童不同的实现
    public abstract void coloring();
}

Specific implementation class: Piglet painted red

public class RedPeiQi extends AbstractPlasterSculpture {

    @Override
    public void coloring() {
        System.out.println("将小猪佩琦雕塑涂成了红色");
    }

}

Specific implementation class: Pig Peppa painted in black

public class BlackPeiQi extends AbstractPlasterSculpture {

    @Override
    public void coloring() {
        System.out.println("将小猪佩琦雕塑涂成了黑色");
    }

}

2.2 Involving roles

(1) AbstractClass (abstract class): A series of basic operations (PrimitiveOperations) are defined in the abstract class. These basic operations can be concrete or abstract. Each basic operation corresponds to a step of the algorithm. Classes can redefine or implement these steps. At the same time, a template method (Template Method) is implemented in the abstract class to define the framework of an algorithm. The template method can not only call the basic methods implemented in the abstract class, but also call the subclasses implemented in the abstract class. Basic methods, and you can also call methods in other objects.

(2) ConcreteClass (concrete subclass): It is a subclass of the abstract class, which is used to implement the abstract basic operations declared in the parent class to complete the steps of the specific algorithm of the subclass, and can also override the concrete already implemented in the parent class. Basic operation.

Pattern Implementation
When implementing the Template Method pattern, there can be collaboration between software designers developing abstract classes and software designers developing concrete subclasses. One designer is responsible for giving the outline and framework of an algorithm, and other designers are responsible for giving the various logical steps of the algorithm. The method that implements these specific logical steps is the basic method, and the method that summarizes these basic methods is the template method, and the name of the template method pattern is also derived from it.

The basic method is the method that implements each step of the algorithm and is part of the template method. There are three basic methods: Abstract Method, Concrete Method and Hook Method.

(1) Abstract method: An abstract method is declared by an abstract class and implemented by its concrete subclasses.
(2) Concrete method: A concrete method is declared and implemented by an abstract class or a concrete class, and its subclasses can be overridden or directly inherited.
(3) Hook method: A hook method is declared and implemented by an abstract class or a concrete class, and its subclasses may be extended. Usually the implementation given in the parent class is an empty implementation (which can be defined as a virtual function using the virtual keyword), and the empty implementation is used as the default implementation of the method. Of course, the hook method can also provide a non-empty default implementation. .

In the template method pattern, there are two types of hook methods: the first type of hook methods can be "hooked" with some specific steps to implement different steps in the template method under different conditions. The return type of such hook methods is usually boolean Type, the name of this type of method is generally IsXXX(), which is used to judge a certain condition. If the condition is satisfied, a certain step will be executed, otherwise it will not be executed, as shown in the following code snippet:

……
//模板方法
public void TemplateMethod() 
{
    Open();
    Display();
    //通过钩子方法来确定某步骤是否执行
    if (IsPrint()) 
    {
        Print();
    }
}

//钩子方法
public bool IsPrint()
{
    return true;
}
……

In the template method pattern, due to object-oriented polymorphism, the subclass object will override the parent class object at runtime, and the method defined in the subclass will also override the method defined in the parent class. The basic method of the class will override the basic method defined in the parent class, and the hook method of the child class will also override the hook method of the parent class, so that the execution of the method of the parent class can be constrained by the hook method implemented in the child class to realize the The class's inverse control over the behavior of the parent class.

2.3 call

caller:

public class Client {
    public static void main(String[] args) {
        AbstractPlasterSculpture redPeiQi = new RedPeiQi();
        redPeiQi.show();
        System.out.println("------------------制作完毕-------------------");

        AbstractPlasterSculpture blackPeiQi = new BlackPeiQi();
        blackPeiQi.show();
        System.out.println("------------------制作完毕-------------------");
    }
}

result:

找些薄的铁皮来,沿着泥塑的高点把铁片插进去
把石膏粉或水一遍一遍的洒在泥塑上面
等干了以后,把在插片处一点一点把几半石膏模分开
在石膏模具里面加点钢筋,缠上麻丝
干了以后再用凿子把磨具敲碎,这样一个石膏雕塑出炉了
将小猪佩琦雕塑涂成了红色
------------------制作完毕-------------------
找些薄的铁皮来,沿着泥塑的高点把铁片插进去
把石膏粉或水一遍一遍的洒在泥塑上面
等干了以后,把在插片处一点一点把几半石膏模分开
在石膏模具里面加点钢筋,缠上麻丝
干了以后再用凿子把磨具敲碎,这样一个石膏雕塑出炉了
将小猪佩琦雕塑涂成了黑色
------------------制作完毕-------------------

Code address: click to jump

References:
[1] Graphical Design Patterns/(Japanese) Hiroshi Yuki; translated by Yang Wenxuan. – Beijing: People’s Posts and Telecommunications Press, 2017.1.
[ 2 ] Wikipedia Design
Patterns [ 3 ] Geek Academy WIKI – Design Patterns .
[ 4 ] Rookie Tutorial – Design Patterns .

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325516965&siteId=291194637