C + + design pattern Shallow knowledge strategy mode

Source: Internet
Author: User
Policy Mode definition:

The algorithm family is defined, separately encapsulated, so that they can replace each other, this mode allows the algorithm to change, does not affect the use of the algorithm of the customer.

The policy pattern contains the following roles:

Context: Environment class

Strategy: Abstract Policy class

Concretestrategy: Specific policy classes

UML Class Diagrams:

Test Cases

[Code]int Main () {//commodity charge double cost;    The cost of taking some kind of charging strategy double result;    if cost = 1029.88; Declare the specific policy class to use//the disadvantage of the policy class is shown here: The client must know what the specific encapsulation algorithm is.    If this example must know three kinds of charge way normal, Return, rebate. Strategycashsuper *normal = new Conerectstrategynormal (cost);//Abstract policy class (base class) pointer to derived class-specific policy class (normal charge mode) Strategycashsuper *return = new Conerectstrategyreturn (cost); Full 300 rebate 100 charge way Strategycashsuper *rebate = new Conerectstrategyrebate (cost);    Call 80 percent charge//Declare the Environment class, the specific invocation of the algorithm, which is maintained by it to the context *c = new context ();    Set the policy class to use C->setstrategy (normal);//set to normal charge//call algorithm result = C->getchargeresult ();    Std::cout << "Accrued expenses:" << result << Std::endl;    C->setstrategy (return);//set to full 300 rebate 100 charge method//Call algorithm result = C->getchargeresult ();    Std::cout << "Accrued expenses:" << result << Std::endl;    C->setstrategy (rebate);//set to hit 80 percent charge//call algorithm result = C->getchargeresult (); Std::cout << "Accrued expenses:" << resUlt << Std::endl; return 0;}

Header file Strategy.h

[Code] #ifndef _2strategy_h_#define _2strategy_h_//policy class, algorithm base class strategycashsuper{protected://commodity payables, defined to protect members for subclass inheritance   Double cost; Public://constructor Strategycashsuper (double c): Cost (c) {}//charge result algorithm virtual double chargeresult ();//This would be defined as pure virtual function, but not. Because the virtual base class cannot instantiate};//normal charge algorithm class Conerectstrategynormal:public Strategycashsuper{public://constructor Conerectstrategynormal (d Ouble c): Strategycashsuper (c) {}//Override the inherited charge algorithm based on the charge method of this class double Chargeresult () override;};/ /full 300 rebate 100 charge algorithm class Conerectstrategyreturn:public Strategycashsuper{public://constructor Conerectstrategyreturn (double c):    Strategycashsuper (c) {}//override charge Algorithm double chargeresult () override; };//80 percent charge algorithm class Conerectstrategyrebate:public Strategycashsuper{public://constructor Conerectstrategyrebate (double c): St  Rategycashsuper (c) {}//override charge Algorithm double chargeresult () override; };//Environment class, according to the specific algorithm, maintenance context uses class Context{private://Policy base class Strategycashsuper *scs;public://Set the policy used by void Setstrateg Y (strategycashsuper *s); The algorithm of the concrete execution double Getchargeresult ();}; #endif

Implement Strategy.cpp

[Code] #include "2Strategy.h"//base class double Strategycashsuper::chargeresult () {    return 0;} Normal charge double Conerectstrategynormal::chargeresult () {    return cost;} Full 300 rebate 100 charge algorithm double Conerectstrategyreturn::chargeresult () {    double res = cost;    if (res >=)        res = cost-100;    return res;} Hit 80 percent charge algorithm double Conerectstrategyrebate::chargeresult () {    return cost *0.8;} Set the algorithm used by void Context::setstrategy (Strategycashsuper *s) {    SCS = s;} The specific execution of the algorithm double Context::getchargeresult () {    return Scs->chargeresult ();}


The strategy model makes the algorithm independent of the customers who use it and becomes a policy model. The policy mode is an object-based behavior pattern.

The policy pattern contains 3 roles: The abstract policy class declares abstract methods for the supported algorithms, and is the parent of all policy classes, and the specific policy class implements the algorithms defined in the abstract policy class. The environment class can employ a variety of policy classes when solving a problem (the disadvantage is that the client needs to know all the encapsulated policy classes) and maintain a reference instance of the abstract policy class in the Environment class.

The strategy pattern is the encapsulation of the algorithm, which divides the responsibility of the algorithm and the algorithm itself, delegating to different object management. The strategy pattern typically encapsulates a series of algorithms into a set of policy classes as subclasses of an abstract policy class.

The main advantage of the strategy model lies in the perfect support of the "open and close principle", which can replace the algorithm or add new algorithm on the basis of not modifying the original system, it manages the family of the algorithm well, improves the reusability of the code, is a substitution inheritance, avoids the multiple conditional transfer statement realization Way , the disadvantage is that the client must know all the policy classes and understand the differences, and at the same time increase the number of classes in the system to some extent, there may be many policy classes.

The application of the policy pattern includes: In a system there are many classes, the difference between them is only their behavior, using the policy mode can be used to dynamically let an object in many behaviors to choose a behavior, a system needs to dynamically select one of several algorithms; avoid using multiple conditional selection statements that are difficult to maintain ; you want to encapsulate the algorithm and the data structures associated with it in a specific policy class.

The above is the C + + design mode of shallow knowledge of the content of the strategy, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.