C++Template (template method) mode-behavioral mode

The template method belongs to the behavioral design pattern, and the behavioral design pattern mainly focuses on the assignment of responsibilities and algorithms among objects. The class behavior model uses inheritance to assign responsibilities between classes, and the template method is a class behavior model. The object behavior model uses composition to assign responsibilities. In the process of our software construction, most of the time we are thinking about the responsibilities between entities, what kind of responsibilities are the most reasonable, not too heavy, not too light, and not ultra vires. In the analysis and design process of object-oriented systems, we often encounter such a situation: for a certain business logic (algorithm implementation) in different objects, there are different implementation details, but the logic (algorithm) framework (or general Application algorithm) is the same. Template provides an implementation framework for this situation. The Template mode uses inheritance to achieve this: Put the logic (algorithm) framework in the abstract base class, define the detailed interface, and implement the details in the subclass. 【Note 1】

        [Note 1]: The Strategy mode solves a similar problem with the Template mode, but the Strategy mode encapsulates the logic algorithm into a class, and uses a combination (delegation) method to solve this problem.

One, what is the template method pattern

The template method pattern defines the skeleton of an algorithm in a method, and delays the implementation of some steps to subclasses. The template method allows subclasses to redefine the specific implementation of certain steps in the algorithm without changing the structure of the algorithm.

When we see the four words "design pattern", we often find it unpredictable, but the template method pattern is an exception. You have to pay attention to only one method .

The template method pattern is indeed very simple, using only the inheritance mechanism , but it is a very widely used pattern.

Second, the usage scenarios of the template method mode

When the framework of the algorithm in the system is fixed, and there may be many implementations of the algorithm, it is necessary to use the template method mode.

  • Multiple subclasses have common methods, and the logic is basically the same
  • For important and complex algorithms, the core algorithm can be designed as a template method, and the surrounding detailed functions are implemented by each subclass
  • When refactoring, the template method is a frequently used method, extracting the same code into the parent class, and then constraining its behavior through the constructor.

Example : A report printing program needs to be made, and the user specifies that the header, text, and footer are required. But the customer's needs will change. One time I want to display the header like this, and another time I want to display it like that. 
At this time, the template method is appropriate.

Three, the advantages and disadvantages of the template method pattern

advantage:

  • Encapsulate the constant part and expand the variable part. The algorithm that considers the constant part is encapsulated into the parent class, and the variable part can be extended through inheritance.
  • Extract the common part of the code for easy maintenance.
  • The behavior is controlled by the parent class and implemented by the subclass

Disadvantages:

The abstract class needs to be modified when the algorithm skeleton needs to be changed.

According to design habits, abstract classes are responsible for declaring the most abstract and general properties and methods of things, and implementation classes are responsible for completing specific transaction properties and methods, but the template method is just the opposite. The result of subclass execution affects the result of the parent class. Will increase the difficulty of code reading.

Fourth, the realization of the template method pattern

AbstractClass class---abstract template class , which defines and implements a template method.
This template is generally a concrete method, which gives a skeleton of the top-level logic, and the logical composition steps are deferred to the subclass implementation in the corresponding abstract operations.
The top-level logic can also call specific methods

#pragma once
//Template.h 
class AbstractClass 
{ 
public: 
	virtual ~AbstractClass(); 
	void TemplateMethod(); 
protected: 
	virtual void PrimitiveOperation1() = 0; 
	virtual void PrimitiveOperation2() = 0; 
	AbstractClass(); 
private: 
}; 
class ConcreteClass1:public AbstractClass 
{ 
public:
	ConcreteClass1(); 
	~ConcreteClass1(); 
protected: 
	void PrimitiveOperation1(); 
	void PrimitiveOperation2(); 
private: 
}; 
class ConcreteClass2:public AbstractClass 
{ 
public: 
	ConcreteClass2(); 
	~ConcreteClass2(); 
protected: 
	void PrimitiveOperation1(); 
	void PrimitiveOperation2(); 
private: 
};
 
#include "stdafx.h"
#include "Template.h" 
#include <iostream>
 
using namespace std; 
AbstractClass::AbstractClass() 
{ 
} 
AbstractClass::~AbstractClass() 
{ 
} 
void AbstractClass::TemplateMethod() 
{ 
	this->PrimitiveOperation1(); 
	this->PrimitiveOperation2(); 
} 
ConcreteClass1::ConcreteClass1() 
{ 
} 
ConcreteClass1::~ConcreteClass1() 
{ 
} 
void ConcreteClass1::PrimitiveOperation1() 
{
	cout<<"ConcreteClass1...PrimitiveOperat ion1"<<endl; 
} 
void ConcreteClass1::PrimitiveOperation2() 
{ 
	cout<<"ConcreteClass1...PrimitiveOperat ion2"<<endl; 
} 
ConcreteClass2::ConcreteClass2() 
{ 
} 
ConcreteClass2::~ConcreteClass2() 
{ 
} 
void ConcreteClass2::PrimitiveOperation1() 
{ 
	cout<<"ConcreteClass2...PrimitiveOperat ion1"<<endl; 
} 
void ConcreteClass2::PrimitiveOperation2()
{ 
	cout<<"ConcreteClass2...PrimitiveOperat ion2"<<endl; 
}
 
int main(int argc, _TCHAR* argv[])
{
	AbstractClass* p1 = new ConcreteClass1(); 
	AbstractClass* p2 = new ConcreteClass2(); 
	p1->TemplateMethod(); 
	p2->TemplateMethod(); 
	return 0;
}

 Since the implementation code of the Template pattern is very simple, the explanation is redundant. The key is to encapsulate the general algorithm (logic), and let the subclass implement the algorithm details (polymorphism).

        The only thing to note is that we define the primitive operation (detailed algorithm) as an unprotected (Protected) member, only for template method calls (subclasses can).

 

      Template mode is a very simple mode, but it is also widely used. As explained in the above analysis and implementation, Template uses inheritance to achieve heterogeneous algorithms. The key point is to encapsulate general algorithms in abstract base classes and place different algorithm details in subclasses for implementation.

      Template mode achieves a reverse control structure effect, which is also a principle DIP (Dependency Inversion Principles) in the analysis and design of object-oriented systems. Its meaning is that the parent class calls the operation of the child class (the operation of the high-level module calling the low-level module), and the low-level module implements the interface declared by the high-level module. In this way, the control right is in the parent class (high-level module), and the low-level module depends on the high-level module instead.

       The mandatory constraint relationship of inheritance also makes the Template mode inadequate. We can see that the primitive method Primitive1() implemented in the ConcreteClass class cannot be reused by other classes. Suppose we want to create a variant of AbstractClass AnotherAbstractClass, and the two are just different in general algorithms, and the primitive operations want to reuse the implementation of the subclass of AbstractClass. But this is impossible, because ConcreteClass inherits from AbstractClass, which also inherits the general algorithm of AbstractClass. AnotherAbstractClass cannot reuse the implementation of ConcreteClass because the latter is not inherited from the former.

        The problems exposed by the Template mode are also inherent problems of inheritance. The Strategy mode uses combination (delegation) to achieve a similar effect to the Template mode. The cost is the cost of space and time. For a detailed discussion of the Strategy mode, please refer to Strategy Schema analysis.

Guess you like

Origin blog.csdn.net/weixin_41882459/article/details/112687938