Implementation of policy Mode C ++ in Design Mode
Strategy: defines the algorithm family and encapsulates them separately so that they can replace each other. This pattern changes the algorithm and does not affect the customers who use the algorithm.
Advantages:
1. unit testing is simplified because each algorithm has its own class and can be tested independently through its own interface.
2. Avoid using multiple conditional transfer statements in the program to make the system more flexible and easy to expand.
3. Therefore, algorithms perform the same job, but implement different tasks. They can call all algorithms in the same way, reducing the coupling between algorithms and algorithm classes.
Disadvantages:
1. Because each specific policy class generates a new class, the number of classes to be maintained by the system is increased.
2. In the basic policy mode, the responsibility for selecting the specific implementation is borne by the client object and transferred to the Context object in the Policy mode.
In the Basic Policy mode, the responsibility for selecting the specific implementation is borne by the client object and transferred to the Context object of the Policy mode. This is not in touch with the pressure that the client needs to choose to judge. After the Strategy Mode is combined with the simple engineering mode, the responsibility for selecting a specific implementation can also be borne by the Context, this minimizes the client's responsibilities.
// Strategy. cpp: defines the entry point of the console application. // # Include stdafx. h # include
Using namespace std; /************************************ policy base class *************************************** */class StrategyBase // mainly defines the virtual function {public: virtual void multiWay_tour () = 0; // It indicates that it is a pure virtual function (a virtual function is not implemented) and must be declared as follows }; /************************************ specific policy class **************************************** /class StrategyFirstChild: public StrategyBase // policy subclass. It mainly implements the virtual methods defined by the parent class {public: void multiWay_tour () {cout <
{Private: StrategyBase * strategyChild; public: Context (StrategyBase * child) {strategyChild = child;} void multiWay_tour () {strategyChild-> multiWay_tour ();}}; /************************************ client * ***************************************/ int main () {cout <Test Program <
MultiWay_tour (); Context_ B-> multiWay_tour (); Context_C-> multiWay_tour ();
delete Context_A;
delete Context_B;
delete Context_C;
cout<