Design Pattern (16) Behavioral Pattern-Template Method Pattern

Foreword

The study of the creation pattern and the structure pattern in the design pattern is completed.
Now we start to study the behavior pattern-template method pattern.


Behavioral model

What is the behavioral model of thinking? Why is it so divided?

The previous creation mode and structure mode:

  • The main focus of the creation model is "how to create objects?", Its main feature is "separate the creation and use of objects"
  • The structured pattern describes how to form classes or objects into a larger structure in a certain layout. It is divided into a class structure pattern and an object structure pattern. The former uses an inheritance mechanism to organize interfaces and classes, and the latter uses composition or aggregation to combine objects.

The behavioral mode is used to describe the complex flow control of the program at runtime, that is, how to work with multiple classes or objects to complete tasks that cannot be completed by a single object individually. It involves the assignment of responsibilities between algorithms and objects

Behavioral patterns are divided into class behavior patterns and object behavior patterns . The former uses inheritance mechanisms to distribute behavior between classes, and the latter uses composition or aggregation to distribute behavior among objects.

Behavioral patterns include: template method pattern, strategy pattern, command pattern, chain of responsibility pattern, state pattern, observer pattern, intermediary pattern, iterator pattern, visitor pattern, memo pattern, interpreter pattern 11 design patterns

These will be understood in later learning, now learn the template method pattern


Problems in reality

As mentioned earlier, the behavioral model is a complex process control in the design description program.

A scenario:
Insert picture description here

An invitation process is abstracted into 3 steps: Order-"Eat-" Buy

For eating different things, the process is the same, only the second step: eating differently

We can define these examples that stipulate the process or format as a template, allowing the template to be designed and changed according to requirements, such as eating noodles, or modifying it to eat a full seat.


Template method pattern

Template Method Pattern : Define the skeleton of the algorithm in an operation, and delay some steps into the subclass. The template method allows the subclass to redefine certain steps of the algorithm without changing the structure of an algorithm

The template method pattern is based on the inherited basic code reuse technology. The structure and usage of the template method pattern is also one of the cores of object-oriented design. In the template method pattern, you can put the same code in the parent class, and put different method implementations in different subclasses

In the template method pattern, we need to prepare an abstract class, implement part of the logic in the form of concrete methods and concrete constructors, and then declare some abstract methods to let the subclasses implement the remaining logic. Different subclasses can implement these abstract methods in different ways, and thus have different implementations of the remaining logic. This is the purpose of the template method pattern. The template method pattern embodies many important ideas of object-oriented and is a pattern with high frequency of use.

Template method pattern structure:
Insert picture description here

The role of the template method pattern:
(1) AbstractClass (AbstractClass): 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, implemented by concrete subclasses.
  • Specific method: It has been implemented in an abstract class, and it can be inherited or rewritten in a concrete subclass.
  • Hook method: Has been implemented in the abstract class, including two logical methods for judgment and empty methods that need subclass rewriting.

(2) Concrete subclass (ConcreteClass): implements the abstract methods and hook methods defined in the abstract class, which are a constituent step of a top-level logic.

It can be seen that there is only an inheritance relationship between classes in the structure diagram, and no object association relationship

Template method pattern implementation

Use the template method pattern to achieve the above guest case.
It is necessary to define an abstract class: the guest process.
Define two specific guests: please eat noodles, please eat Han Han full seats

Insert picture description here

package com.company.Behavioral;
//抽象类:定义模板
abstract class Treat {
    //请客模板
   final  public void treatEat(){
        //请客的具体流程:点单 - 》 吃菜 - 》 买单
        order();
        eat();
        pay();
    }
    //具体流程:点单方法
    private void order(){
        System.out.println(" 服务员,点菜。。。");
    }
    //具体流程:抽象方法,由子类具体实现
    abstract void eat();
    //具体流程:买单方法
    private void pay(){
        System.out.println(" 这餐我买单。。。 ");
    }
}
//具体实现类:请吃面条
class TreatNoodles extends Treat{
    private String food = "noodles";

    @Override
    void eat() {
        System.out.println(" 今天,我请大家吃 "+food+"。。。");
    }
}
//具体实现类:请吃满汉全席
class TreatFull extends Treat{
    private String food = "满汉全席";
    @Override
    void eat() {
        System.out.println(" 今天,我请大家吃 "+food+"。。。");
    }
}

class Client{
    public static void main(String[] args) {
        Treat treatNoodles = new TreatNoodles();
        treatNoodles.treatEat();
    }
}

Insert picture description here

The template method pattern is very simple, mainly to give the general process of the template through the abstract class, and then implement specific methods by the subclass


Hook method extension template method pattern

Hook method: Do nothing by default, subclasses can choose whether to override this method according to the situation, through this method to control the flow of the parent class

The specific process is defined in the previous abstract class. If there are certain changes to the process, you can use hook method constraints to restrict the execution of the parent class method through the hook method implemented in the subclass to implement the subclass's behavior on the parent class. Reverse control

For example: add a process to drink before eating,
you can use a judgment method (hook method) to decide whether to drink

package com.company.Behavioral;
//抽象类:定义模板
abstract class Treat {
    //请客模板
    final public void treatEat(){
        //请客的具体流程:点单 - 》 吃菜 - 》喝酒- 》 买单
        order();
        //钩子方法决定是否喝酒
        if (isDrink()){
            drink();
        }
        eat();
        pay();
    }
    //具体流程:点单方法
    private void order(){
        System.out.println(" 服务员,点菜。。。");
    }
    //具体流程:喝酒
    private void drink(){
        System.out.println(" 来来来,干了这杯82年的老白干。。。");
    }
    //具体流程:抽象方法,由子类具体实现
    abstract void eat();
    //具体流程:买单方法
    private void pay(){
        System.out.println(" 这餐我买单。。。 ");
    }
    //钩子方法
    public boolean isDrink(){
        return true;
    }

}
//具体实现类:请吃面条
class TreatNoodles extends Treat{
    private String food = "noodles";

    @Override
    void eat() {
        System.out.println(" 今天,我请大家吃 "+food+"。。。");
    }
    @Override
    public boolean isDrink(){
        return false;
    }
}
//具体实现类:请吃满汉全席
class TreatFull extends Treat{
    private String food = "满汉全席";
    @Override
    void eat() {
        System.out.println(" 今天,我请大家吃 "+food+"。。。");
    }
}

class Client{
    public static void main(String[] args) {
        //吃面条就别喝酒了
        Treat treatNoodles = new TreatNoodles();
        treatNoodles.treatEat();
        System.out.println("-------------------");
        //吃满汉全席一定要喝酒
        Treat treatFull = new TreatFull();
        treatFull.treatEat();
    }
}

Insert picture description here

The hook method is that simple


The advantages and disadvantages of the template method pattern

advantage

  • The template method pattern defines the algorithm formally in a class, while its subclasses implement the details.
  • The template method pattern is a basic technique of code reuse .
  • The template method pattern leads to a reverse control structure, calling the operations of its subclasses through a parent class, and adding new behaviors through the expansion of the subclasses, in line with the "opening and closing principle"

Disadvantages

  • Each different implementation needs to define a subclass, which will lead to an increase in the number of classes, a larger system, and a more abstract design , but it is more in line with the "single responsibility principle", which improves the cohesion of the class
  • The abstract method in the parent class is implemented by the child class, and the result of the child class execution will affect the result of the parent class , which leads to a reverse control structure, which increases the difficulty of code reading
  • Because it is achieved by rewriting the parent class through inheritance, it violates the "Lee's replacement principle" , and because it is inherited, it violates the "composite reuse principle" idea.

Applicable environment

The following scenarios apply to the template method mode:

  • Implement the constant part of an algorithm at once and leave the variable behavior to subclasses
  • The common behavior in each subclass should be extracted and concentrated into a common parent class to avoid code duplication
  • Split some complex algorithms , design the fixed part of the algorithm as template method and parent specific method, and some details that can be changed are implemented by its subclass
  • Control the expansion of subclasses

Specific use

The template method pattern is very simple and very practical. This pattern is frequently used in many frameworks (Spring, Struts, etc.).
As long as the complex algorithm has a common part, you can use the module method pattern. In fact, it is often used in actual programming. The idea of ​​the module method pattern

The template method pattern used in the initialization of the Spring IOC container


Pattern extension knowledge

  1. inherit

It is often said that the Richter's replacement principle: inheritance should not override the parent class method. The
composite reuse principle: you should first consider aggregation and composition, and then consider inheritance

The template method pattern encourages us to use inheritance appropriately. This pattern can be used to rewrite some related classes with the same function, move the reusable general behavior code to the parent class, and move the special behavior code to the subclass. inside. This also further shows that although there are some problems with inheritance reuse, it can still bring convenience to developers in some cases . The template method pattern is one of the modes that reflects the advantages of inheritance.

  1. Hollywood Principles

The Hollywood principle is defined as: "Don't call us, we'll call you"

In the template method pattern, the subclass implements some specific business logic by rewriting the method of the parent class. The
specific process is controlled in the parent class, and the parent class controls the call to the subclass

The Hollywood principle is reflected in: the subclass does not need to call the parent class, but the subclass is called through the parent class; the parent class controls the entire process


Mode details

  1. The basic idea is: the algorithm only exists in one place, that is, in the parent class, it is easy to modify . When you need to modify the algorithm, as long as you modify the template method of the parent class or some steps that have been implemented, the subclass will inherit these modifications
  2. Achieve maximum code reuse . The template method of the parent class and some steps that have been implemented will be inherited by the child class and used directly.
  3. It not only unifies the algorithm, but also provides great flexibility . The template method of the parent class ensures that the structure of the algorithm remains unchanged, while the subclasses provide part of the implementation of the steps.
  4. The shortcomings of this pattern: each different implementation requires a subclass implementation , resulting in an increase in the number of classes, making the system more bulky
  5. The general template method adds the final keyword to prevent subclasses from overriding the template method.
  6. Template method pattern usage scenario: When a process is to be completed, the process needs to perform a series of steps, the series of steps are basically the same, but the individual steps may be different in the implementation, usually consider using the template method pattern to deal with

to sum up

  • There are 11 specific design patterns in the behavioral mode, which mainly describe the complicated process control in the program operation.
  • The template method pattern is to define an algorithm skeleton, process, and implement specific steps in subclasses.
  • The template method pattern has two roles: abstract class: responsible for giving the skeleton of the algorithm, which is composed of a final template method and a specific method. The specific method can define a hook method (used by the subclass to control the parent class process), and define an abstract method (by Specific steps completed by subclasses); specific implementation classes: implement some specific steps
  • The advantage of the template method pattern is that the subclass does not change the structure of the algorithm when defining a detailed processing algorithm, and realizes code reuse. By extending the subclass, new behaviors can be added, which conforms to the "opening and closing principle"
  • The disadvantage of the template method pattern is that each different implementation defines a subclass, which makes the system complex and huge, and the design is more abstract, and because it is inherited and rewritten, it violates the Richter's replacement principle and the principle of composite reuse; the template method pattern Should be used in specific scenarios
  • The template method pattern is suitable for scenarios: complex algorithm partitioning algorithm; common behavior extraction concentrated on common parent class to avoid code duplication; control subclass expansion
  • The template method pattern is used in many frameworks, and the idea of ​​the template method pattern is more or less used in our actual programming.
Published 121 original articles · won 31 · views 7869

Guess you like

Origin blog.csdn.net/key_768/article/details/105404734