Template Method Design Pattern

Original address: http://blog.csdn.net/lovelion/article/details/8299794

1. Overview of Template Method Pattern

       In real life, many things involve several implementation steps, such as inviting guests to dinner, no matter what to eat, it generally includes several steps such as ordering, eating, and paying. Usually, the order of these steps is: ordering --> Eat --> Pay. In these three steps, ordering and paying are similar, the biggest difference lies in the second step - what to eat? Eating noodles is quite different from eating Manchurian feasts, as shown in Figure 1:

Figure Schematic diagram of inviting guests to dinner

        In software development, a similar situation is sometimes encountered. The implementation of a method requires multiple steps (similar to "treating a guest"), some of which are fixed (similar to "ordering" and "paying"), while some The steps are not fixed, there is variability (like "eating") . In order to improve the reusability of the code and the flexibility of the system, a design pattern called the template method pattern can be used to design such cases. In the template method pattern, the corresponding Methods are called base methods (such as "Order", "Eat", and "Pay"), and methods that call these base methods while defining the order in which the base methods are executed are called template methods (such as "Treat"). In the template method pattern, you can put the same code in the parent class, for example, put the template method "treat" and the implementation of the basic methods "order" and "pay" in the parent class, and for the basic method "eat" ", make only one declaration in the parent class, put its concrete implementation in different subclasses, provide the implementation of "eat noodles" in one subclass, and provide the implementation of "eat the Manchurian banquet" in the other subclass. By using the template method pattern, on the one hand, the reusability of the code is improved; Flexibility and scalability.

       The template method pattern is defined as follows:

Template Method Pattern: Define the skeleton of an algorithm in an operation , while deferring some steps to subclasses. The Template Method pattern allows subclasses to redefine certain steps of an algorithm without changing its structure.

 

Template Method Pattern:  Define the skeleton of an algorithm in an  operation, deferring some steps to subclasses. Template Method lets  subclasses redefine certain steps of an algorithm without changing the  algorithm's structure.

       Template method pattern is a code reuse technology based on inheritance , which is a class behavior pattern .

       The template method pattern is the simplest behavioral design pattern, in which 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, and 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 certain 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 implementation of some specific steps can be done in its subclasses.

 

2. Template method pattern structure and implementation

2.1 Pattern structure

      The structure of the template method pattern is relatively simple, and its core is the design of the abstract class and the template method in it. Its structure is shown in Figure 2 :

Figure Template method pattern structure diagram

      由图2可知,模板方法模式包含如下两个角色:

       (1) AbstractClass(抽象类)在抽象类中定义了一系列基本操作(PrimitiveOperations),这些基本操作可以是具体的,也可以是抽象的,每一个基本操作对应算法的一个步骤,在其子类中可以重定义或实现这些步骤。同时,在抽象类中实现了一个模板方法(Template Method),用于定义一个算法的框架,模板方法不仅可以调用在抽象类中实现的基本方法,也可以调用在抽象类的子类中实现的基本方法,还可以调用其他对象中的方法。

       (2) ConcreteClass(具体子类)它是抽象类的子类,用于实现在父类中声明的抽象基本操作以完成子类特定算法的步骤,也可以覆盖在父类中已经实现的具体基本操作。

 

2.2 模式实现

       在实现模板方法模式时,开发抽象类的软件设计师和开发具体子类的软件设计师之间可以进行协作。一个设计师负责给出一个算法的轮廓和框架,另一些设计师则负责给出这个算法的各个逻辑步骤。实现这些具体逻辑步骤的方法即为基本方法,而将这些基本方法汇总起来的方法即为模板方法,模板方法模式的名字也因此而来。下面将详细介绍模板方法和基本方法:

       1. 模板方法

       一个模板方法是定义在抽象类中的、把基本操作方法组合在一起形成一个总算法或一个总行为的方法。这个模板方法定义在抽象类中,并由子类不加以修改地完全继承下来。模板方法是一个具体方法,它给出了一个顶层逻辑框架,而逻辑的组成步骤在抽象类中可以是具体方法,也可以是抽象方法。由于模板方法是具体方法,因此模板方法模式中的抽象层只能是抽象类,而不是接口。

         2. 基本方法

       基本方法是实现算法各个步骤的方法,是模板方法的组成部分。基本方法又可以分为三种:抽象方法(Abstract Method)、具体方法(Concrete Method)和钩子方法(Hook Method)

       (1) 抽象方法:一个抽象方法由抽象类声明、由其具体子类实现。在C#语言里一个抽象方法以abstract关键字标识。

       (2) 具体方法:一个具体方法由一个抽象类或具体类声明并实现,其子类可以进行覆盖也可以直接继承。

       (3) 钩子方法:一个钩子方法由一个抽象类或具体类声明并实现,而其子类可能会加以扩展。通常在父类中给出的实现是一个空实现(可使用virtual关键字将其定义为虚函数),并以该空实现作为方法的默认实现,当然钩子方法也可以提供一个非空的默认实现。

       在模板方法模式中,钩子方法有两类:第一类钩子方法可以与一些具体步骤“挂钩”,以实现在不同条件下执行模板方法中的不同步骤,这类钩子方法的返回类型通常是bool类型的,这类方法名一般为IsXXX(),用于对某个条件进行判断,如果条件满足则执行某一步骤,否则将不执行,如下代码片段所示:

[csharp]  view plain  copy
 
  1. ……  
  2. //模板方法  
  3. public void TemplateMethod()   
  4. {  
  5. Open();  
  6. Display();  
  7. //通过钩子方法来确定某步骤是否执行  
  8. if (IsPrint())   
  9. {  
  10.     Print();  
  11. }  
  12. }  
  13.   
  14. //钩子方法  
  15. public bool IsPrint()  
  16. {  
  17.     return true;  
  18. }  
  19. ……  

        在代码中IsPrint()方法即是钩子方法,它可以决定Print()方法是否执行,一般情况下,钩子方法的返回值为true,如果不希望某方法执行,可以在其子类中覆盖钩子方法,将其返回值改为false即可,这种类型的钩子方法可以控制方法的执行,对一个算法进行约束。

       还有一类钩子方法就是实现体为空的具体方法,子类可以根据需要覆盖或者继承这些钩子方法,与抽象方法相比,这类钩子方法的好处在于子类如果没有覆盖父类中定义的钩子方法,编译可以正常通过,但是如果没有覆盖父类中声明的抽象方法,编译将报错。

       在模板方法模式中,抽象类的典型代码如下:

[csharp]  view plain  copy
 
  1. abstract class AbstractClass   
  2. {  
  3. //模板方法  
  4. public void TemplateMethod()   
  5. {  
  6.         PrimitiveOperation1();  
  7.         PrimitiveOperation2();  
  8.         PrimitiveOperation3();  
  9. }  
  10.   
  11. //基本方法—具体方法  
  12. public void PrimitiveOperation1()   
  13. {  
  14.     //实现代码  
  15. }  
  16.   
  17. //基本方法—抽象方法  
  18.     public abstract void PrimitiveOperation2();      
  19.   
  20. //基本方法—钩子方法  
  21. public virtual void PrimitiveOperation3()     
  22. {  }  
  23. }  

        在抽象类中,模板方法TemplateMethod()定义了算法的框架,在模板方法中调用基本方法以实现完整的算法,每一个基本方法如PrimitiveOperation1()PrimitiveOperation2()等均实现了算法的一部分,对于所有子类都相同的基本方法可在父类提供具体实现,例如PrimitiveOperation1(),否则在父类声明为抽象方法或钩子方法,由不同的子类提供不同的实现,例如PrimitiveOperation2()PrimitiveOperation3()

        可在抽象类的子类中提供抽象步骤的实现,也可覆盖父类中已经实现的具体方法,具体子类的典型代码如下:

[csharp]  view plain  copy
 
  1. class ConcreteClass : AbstractClass   
  2. {  
  3. public override void PrimitiveOperation2()   
  4. {  
  5.     //实现代码  
  6. }  
  7.   
  8. public override void PrimitiveOperation3()   
  9. {  
  10.     //实现代码  
  11. }  
  12. }  

       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 Class reverse control of parent class behavior

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326605481&siteId=291194637