zoukankan      html  css  js  c++  java
  • 设计模式C++描述----15.策略(Strategy)模式

    一. 举例说明

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

    结构如下:


    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类)。

  • 相关阅读:
    OSCP Learning Notes Buffer Overflows(3)
    OSCP Learning Notes Buffer Overflows(5)
    OSCP Learning Notes Exploit(3)
    OSCP Learning Notes Exploit(4)
    OSCP Learning Notes Exploit(1)
    OSCP Learning Notes Netcat
    OSCP Learning Notes Buffer Overflows(4)
    OSCP Learning Notes Buffer Overflows(1)
    OSCP Learning Notes Exploit(2)
    C++格式化输出 Learner
  • 原文地址:https://www.cnblogs.com/any91/p/3248003.html
Copyright © 2011-2022 走看看