1. Implement Template Method mode by NVi method
Template Method Mode
There are different details implementations of a business logic (algorithm implementation) in different objects, but the logical (algorithmic) framework (or general application algorithm) is the same. The Template method provides an implementation framework for this scenario.
The Template method pattern is implemented in an inherited way: the logical (algorithmic) framework is placed in the abstract base class, and the details of the interface are defined, and the details are implemented in subclasses.
The key point is to encapsulate the generic algorithm in the abstract base class
The non_virtual function used in the NVI technique becomes the external application of the virtual function.
The advantage of the NVI technique is that
The external device ensures that the scene is set before a virtual function is called and cleans up after the call is finished.
2. implement strategy mode by function pointer
Strategy mode
The strategy pattern solves a problem similar to the template method pattern, but the strategy pattern is to encapsulate the logic (algorithm) into a class and take a combination (delegate) approach to solve the problem.
To implement an abstract interface, inheritance is a way: we declare an abstract interface in a base class and place specific implementations in a specific subclass. A combination (delegate) is another way: we place the implementation of the interface in the combined object, placing the abstract interface in the composition class.
3. completed strategy mode by Std:function
throughstd::functionencapsulation of various callable entities (ordinary functions, lambda expressions, function pointers, and other function objects) in C + + to form a new callablestd::functionobject;
about callable entities converted to std::function objects are subject to the following two principles:
The converted std::function
The return value of the callable entity can be converted to std::function The return value of the object.
std::function implements a set of type elimination mechanisms that can handle different types of function objects uniformly.
Efective C + + clause 35: Consider alternatives other than the virtual function