• 策略模式


    定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法的变化不会影响到使用算法的客户

    代码:

    #include <iostream>
    using namespace std;
    
    class Strategy
    {
    public:
        virtual ~Strategy() {}
    public:
        virtual void encrypt() = 0; //加密
    };
    
    //对称加密  速度快 加密大数据块文件 特点:加密密钥和解密密钥是一样的.
    //非对称加密 加密速度慢 加密强度高 高安全性高 ;特点: 加密密钥和解密密钥不一样  密钥对(公钥 和 私钥)
    
    class AES : public Strategy
    {
    public:
        virtual void encrypt()
        {
            cout << "使用AES算法加密" << endl;
        }
    };
    
    class MD5 : public Strategy
    {
    public:
        virtual void encrypt()
        {
            cout << "使用MD5算法加密" << endl;
        }
    };
    
    class Context
    {
    public:
        void setStrategy(Strategy *s)
        {
            _strategy = s;
        }
    
        void operate()
        {
            if (_strategy != NULL)
            {
                _strategy->encrypt();
            }
        }
    private:
        Strategy *_strategy;
    };
    
    void test()
    {
        Strategy *strategy = NULL;
        Context *context = NULL;
        context = new Context();
        strategy = new AES();
        context->setStrategy(strategy);
        context->operate();
        delete strategy;
        strategy = new MD5();
        context->setStrategy(strategy);
        context->operate();
        delete strategy;
        delete context;
    }
    
    int main()
    {
        test();
        cin.get();
        return 0;
    }
  • 相关阅读:
    SQL语句执行效率及分析(note)
    双重检查锁定及单例模式
    可定制生命周期的缓存
    php CI框架高级视图功能,视图继承,多重继承,视图片段
    php 使用pdo连接postgresql
    python 学习整理
    phpmailer 发送邮件
    php syslog记录系统日志
    php 学习整理
    php 生成唯一id方法
  • 原文地址:https://www.cnblogs.com/hupeng1234/p/6814390.html
Copyright © 2020-2023  润新知