Design pattern (twenty-three) template method pattern

Template Method Pattern

1. What is the template method pattern

Template Method Pattern: Define the framework of an algorithm in operation, and delay some steps to subclasses. The template method pattern allows subclasses to redefine certain specific steps of an algorithm without changing the structure of the algorithm.

The template method pattern is a code reuse technology based on inheritance, and it is a kind of behavioral pattern.

The template method pattern is the simplest behavioral design pattern. In its structure, there is only the inheritance relationship between the parent class and the child class. By using the template method pattern, the implementation steps of some complex processes can be encapsulated in a series of basic methods. A method called template method is provided in the abstract parent class to define the execution order of these basic methods, and through its subclasses To cover some steps, so that the same algorithm framework can have different execution results. The template method pattern provides a template method to define the algorithm framework, and the realization of some specific steps can be completed in its subclasses.

In the template method mode, 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. Therefore, the specific child 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. Thus, the execution of the parent class method can be restricted by the hook method implemented in the child class. The reverse control of the behavior of the parent class by the class.

2. Template method pattern role analysis

Structure diagram of template method mode:
Template method pattern

  • 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, which can be in its subclass 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, you can also call methods in other objects.

  • ConcreteClass (concrete subclass): It is a subclass of the abstract class, used to implement the abstract basic operations declared in the parent class to complete the steps of the subclass specific algorithm, and it can also cover the specific basic operations that have been implemented in the parent class.

  • Template method
    A template method is a method defined in an abstract class that combines basic operation methods to form a general algorithm or a general behavior. This template method is defined in the abstract class and is completely inherited by subclasses without modification. The template method is a concrete method, which gives a top-level logical framework, and the logical composition steps can be concrete methods or abstract methods in abstract classes. Because template methods are concrete methods, the abstraction layer in the template method pattern can only be abstract classes, not interfaces.

  • Basic method The
    basic method is a method to implement the various steps of the algorithm, and is an integral part of the template method.
    The basic methods can be divided into three types: 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. An abstract method in C# language is identified by the abstract keyword.
    2. Concrete method: A concrete method is declared and implemented by an abstract or concrete class, and its subclasses can be overridden or inherited directly.
    3. Hook method: A hook method is declared and implemented by an abstract or concrete class, and its subclasses may be extended. Usually the implementation given in the parent class is an empty implementation (it 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 .

There are generally two hook methods:

  • The first type of hook method can be "hooked" with some specific steps to implement different steps in the template method under different conditions. The return type of this type of hook method is usually bool type, and the name of this type of method is generally IsXXX() , Used to judge a certain condition, if the condition is met, execute a certain step, otherwise it will not execute.
public void TemplateMethod() {
    
    
    Open();
    Display();
    //通过钩子方法来确定某步骤是否执行
    if (IsPrint()) {
    
    
      Print();
    }
}
 
//钩子方法,返回boolean值
protected bool IsPrint(){
    
    
    return true;
}
  • Another type of hook method is a specific method whose implementation body is empty. Subclasses can override or inherit these hook methods as needed.
abstract class AbstractClass {
    
    
    //模板方法
    public void TemplateMethod() {
    
    
        PrimitiveOperation1();
        PrimitiveOperation2();
        PrimitiveOperation3();
    }
 
    //基本方法—具体方法
    public void PrimitiveOperation1() {
    
    
        //实现代码
    }
 
    //基本方法—抽象方法
    public abstract void PrimitiveOperation2();    
 
    //基本方法—钩子方法
    public virtual void PrimitiveOperation3()   {
    
    
    }
}

3. Advantages and disadvantages of template method pattern

advantage:

  • An algorithm is formally defined in the parent class, and its subclasses implement detailed processing. When the subclass implements the detailed processing algorithm, the execution order of the steps in the algorithm will not be changed.
  • The template method pattern is a code reuse technology, which is particularly important in class library design. It extracts the public behaviors in the class library, puts the public behaviors in the parent class, and implements different behaviors through its subclasses. It encourages us to use inheritance appropriately to achieve code reuse.
  • A kind of reverse control structure can be realized, and the hook method of the subclass overrides the parent class to determine whether a particular step needs to be executed.
  • In the template method pattern, the basic methods of the parent class can be overridden by subclasses. Different subclasses can provide different implementations of the basic methods. It is convenient to replace and add new subclasses and conform to the single responsibility principle and the principle of opening and closing.

Disadvantages: It is
necessary to provide a subclass for different implementations of each basic method. If there are too many variable basic methods in the parent class, the number of classes will increase, the system will be larger, and the design will be more abstract. Design in combination with bridging mode.

Applicable scene:

  • To segment some complex algorithms, design the fixed part of the algorithm as a template method and a specific method of the parent class, and some details that can be changed are implemented by its subclasses. That is: implement the invariant part of an algorithm at a time, and leave the variable behavior to subclasses to implement.
  • Common behaviors in each subclass should be extracted and concentrated into a common parent class to avoid code duplication.
  • It is necessary to determine whether a certain step in the algorithm of the parent class is executed through the subclass, and realize the reverse control of the subclass to the parent class.

4. Practical impression

Used often, very frequently. Need to control the realization of the parent class in the development, you must consider all aspects. Because more than the parent class has more than one child class.

5. Code example

slightly…

Guess you like

Origin blog.csdn.net/u014099894/article/details/85208649