wanlifeipeng

  博客园 :: 首页 :: 博问 :: 闪存 :: :: 联系 :: 订阅 订阅 :: 管理 ::

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

代码:

#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;
}

 

posted on 2017-05-05 18:16  wanlifeipeng  阅读(132)  评论(0编辑  收藏  举报