zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C++设计模式实现--策略(Strategy)模式

C++模式设计模式 实现 -- 策略 Strategy
2023-09-27 14:27:22 时间
版权声明:本文为博主原创文章,未经博主同意不得转载。 https://blog.csdn.net/L_Andy/article/details/30489331

一. 举例说明

曾经做了一个程序,程序的功能是评价几种加密算法时间。程序的使用操作不怎么变,变的是选用各种算法。

结构例如以下:


Algorithm:抽象类。提供算法的公共接口。

RSA_Algorithm:详细的RSA算法。

DES_Algorithm:详细的DES算法。

BASE64_Algorithm:详细的Base64算法。

在使用过程中。我仅仅须要对外发布Algorithm_Context这个类及接口就可以。


代码实现:

  1. //策略类  
  2. class Algorithm    
  3. {  
  4. public:  
  5.     virtual void calculate() = 0;    
  6. };  
  7.   
  8. //详细RSA算法  
  9. class RSA_Algorithm : public Algorithm    
  10. {    
  11. public:    
  12.     void calculate() { cout<<"RSA algorithm..."<<endl; }    
  13. };    
  14.   
  15. //详细DES算法  
  16. class DES_Algorithm : public Algorithm    
  17. {    
  18. public:    
  19.     void calculate() { cout<<"DES algorithm..."<<endl; }    
  20. };  
  21.   
  22. //详细Base64算法  
  23. class BASE64_Algorithm: public Algorithm    
  24. {    
  25. public:  
  26.     void calculate() { cout<<"Base64 algorithm..."<<endl; }    
  27. };   
  28.   
  29. //策略上下文  
  30. class Algorithm_Context  
  31. {  
  32. private:  
  33.     Algorithm *m_ra;  
  34.   
  35. public:  
  36.     Algorithm_Context(Algorithm *ra) { m_ra = ra; }  
  37.     ~Algorithm_Context() { delete m_ra; }  
  38.       
  39.     void calculate() { m_ra->calculate(); }  
  40. };  
  41.   
  42. //測试代码  
  43. int main()  
  44. {  
  45.     Algorithm_Context context(new RSA_Algorithm()); //使用详细算法  
  46.       
  47.     context.calculate();  
  48.       
  49.     return 0;    
  50. }    

一. 策略模式

定义:它定义了算法家族,分别封装起来,让它们之间能够互相替换。此算法的变化。不会影响到使用算法的客户


这里的关键就是将算法的逻辑抽象接口(DoAction)封装到一个类中(Context)。再通过托付的方式将详细的算法实现托付给详细的 Strategy 类来实现(ConcreteStrategeA类)。

策略模式是一种定义一系列算法的方法,从概念上来看。全部这些算法完毕的都是同样的工作,仅仅是实现不同,它能够以同样
的方式调用全部的算法。降低了各种算法类与使用算法类之间的耦合。


策略模式的长处是简化了单元測试,由于每一个算法都有自己的类,能够通过自己的接口单独測试。
策略模式就是用来封装算法的,但在实践中,我们发现能够用它来封装差点儿不论什么类型的规则。仅仅要在分析过程中听到须要在不同实践应用不同
的业务规则,就能够考虑使用策略模式处理这样的变化的可能性。