Explain the advantages and disadvantages of the strategy pattern in C + + design pattern programming and implement _c language

Source: Internet
Author: User
Tags mongodb postgresql redis firewall


Policy mode (strategy): It defines a series of algorithms, encapsulates each algorithm, and makes them interchangeable. The policy pattern allows the algorithm to change without affecting the client using the algorithm. The problem with the policy pattern and the Template pattern is the same (similar), all for the purpose of decoupling the business logic (algorithm) from the abstract interface. The strategy mode encapsulates the logic (algorithm) into a class (context), implements the implementation of the specific algorithm in the composite object by combining the method, and then delegates the implementation of the abstract interface to the composite object through the delegate. The state pattern also has a similar function, and the difference between them will be given in the discussion.


UML diagrams
Advantages:

1, simplified unit testing, because each algorithm has its own class, can be tested by their own interface.
2, avoid the use of multiple conditional transfer statements in the program, making the system more flexible and easy to expand.
3, adhere to most grasp principles and common design principles, high cohesion, low coupling.
Disadvantages:
1, because each specific policy class will produce a new class, it will increase the number of classes the system needs to maintain.
2, in the basic policy model, the choice of the specific implementation of the responsibility to be borne by the client object, and transferred to the policy mode of the context object



Implementation example:
Strategy.h


#include <iostream> #include <string> #include <memory> using namespace std; 
  Strategy abstract class, used as interface class strategy {public:virtual string Substitute (string str) = 0; 
  Virtual ~strategy () {cout<< "in the destructor of strategy" <<endl; 
 
} 
}; 
    Class Chinesestrategy:public Strategy {public:string Substitute (string str) {int Index=str.find ("520"); 
    String Tempstr=str.replace (index,3, "I Love You"); 
  return tempstr; 
  } ~chinesestrategy () {cout<< "in the destructor of Chinesestrategy" <<endl; 
 
} 
}; 
    Class Englishstrategy:public Strategy {public:string Substitute (string str) {int Index=str.find ("520"); 
    String Tempstr=str.replace (index,3, "I love ou"); 
  return tempstr; 
  } ~englishstrategy () {cout<< "in the destructor of Chinesestrategy" <<endl; 
 
} 
}; 

     Context Classes class Translator {private:auto_ptr<strategy> strategy; In the customerCode to add a pointer to the type of algorithm (stategy). 
  Public: ~translator () {cout<< "in the destructor of Translator" <<endl; 
  } void Set_strategy (Auto_ptr<strategy> strategy) {this->strategy=strategy; 
    String translate (String str) {if (0==strategy.get ()) return ""; 
  return Strategy->substitute (str); 

 } 
};


Strategy.cpp


#include "Strategy.h" 
 
int main (int argc, char *argv) 
{ 
  string str ("321520"); 
  Translator *translator=new Translator; 
  cout<< "No strategy" when strategy is not specified <<endl; 
  Translator->translate (str); 
  cout<< "---------------" <<endl; 
   
  Translated into Chinese 
  auto_ptr<strategy> S1 (new chinesestrategy); 
  Translator->set_strategy (S1); 
  cout<< "Chinese strategy" <<endl; 
  Cout<<translator->translate (str) <<endl; 
  cout<< "---------------" <<endl; 
 
  Translated into English 
  auto_ptr<strategy> S2 (new englishstrategy); 
  Translator->set_strategy (S2); 
  cout<< "中文版 strategy" <<endl; 
  Cout<<translator->translate (str) <<endl; 
  cout<< "----------------" <<endl; 
 
  Delete translator; 
  return 0; 
 
}  

Discussion on the strategy model

You can see that the policy and Template patterns solve similar problems, and as analyzed in the Template model, the policy and Template patterns are actually two ways to implement an abstract interface: the difference between inheritance and composition. To implement an abstract interface, inheritance is a way: we declare an abstract interface in a base class and place the implementation in a specific subclass. The combination (delegate) is another way: we put the implementation of the interface in the grouped object and put the abstract interface in the composition class. Each of these two ways has its advantages and disadvantages, first listed:
1. Inheritance:
Advantages: Easy to modify and extend those implementations that are reused.
Disadvantage: The ① destroys the encapsulation, and the implementation details of the parent class are exposed to subclasses in the inheritance; ② "white box" reuse, cause in 1; ③ when the implementation of the parent class changes, all of its subclasses will have to be changed; ④ inherited from the parent class cannot be changed during run time (as determined during compilation).
2. Combination:
Advantages: ① "black box" reuse, because the internal details of the contained object are not visible externally; ② encapsulation is good, because 1) ③ implementations and abstractions are small dependencies (small dependencies between grouped objects and grouped objects); ④ can dynamically define implementations during run time (through a pointer to the same type. Typically a pointer to an abstract base class).
Disadvantage: Too many objects in the system.



From the above, we can see that the combination of inheritance can achieve better results, so in object-oriented design there is a very important principle is: the use of (object) combination, rather than (Class) inheritance (Favorcomposition over inheritance).



In fact, inheritance is a compelling way to make a strong coupling between a base class and a specific subclass. For example, primitives that are defined in ConcreteClass1 in Template method mode cannot be reused directly (unless you inherit from AbstractClass, see Template Method schema documentation for specific analysis). The combination (delegate) of the way there is a very small coupling, implementation (concrete implementation) and interface (abstract interface) between the dependence is very small, for example, in this implementation, Concretestrategya implementation of the specific operations are easily reused by other classes, such as we want to define another context class Anothercontext, simply combining a pointer to a strategy can easily reuse Concretestrategya implementations.



The difference between inheritance and composition is illustrated in our analysis of bridging pattern problems and bridging patterns. Refer to the corresponding mode resolution.



In addition, there are similarities in the state mode of the policy pattern, but the state mode focuses on the different operations of the objects in different states. The difference between the two is that there is a reference to the context in the implementation class in the state pattern, and the policy pattern is not. For specific analysis, please refer to the corresponding state mode analysis.


Alibaba Cloud Hot Products

Elastic Compute Service (ECS) Dedicated Host (DDH) ApsaraDB RDS for MySQL (RDS) ApsaraDB for PolarDB(PolarDB) AnalyticDB for PostgreSQL (ADB for PG)
AnalyticDB for MySQL(ADB for MySQL) Data Transmission Service (DTS) Server Load Balancer (SLB) Global Accelerator (GA) Cloud Enterprise Network (CEN)
Object Storage Service (OSS) Content Delivery Network (CDN) Short Message Service (SMS) Container Service for Kubernetes (ACK) Data Lake Analytics (DLA)

ApsaraDB for Redis (Redis)

ApsaraDB for MongoDB (MongoDB) NAT Gateway VPN Gateway Cloud Firewall
Anti-DDoS Web Application Firewall (WAF) Log Service DataWorks MaxCompute
Elastic MapReduce (EMR) Elasticsearch

Alibaba Cloud Free Trail

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.