简介
策略模式(Strategy Pattern)中,一个类的行为或其算法可以在运行时更改。其定义了一系列算法,并将每个算法封装起来,使他们可以相互替换,且算法的变化不会影响到使用算法的客户。
角色与职责
Strategy:算法抽象类
OperatorAdd:具体算法实现类
实现
#include <iostream>
using std::cout;
using std::endl;
class Strategy {
public:
virtual void Crypto() = 0;
};
class AES : public Strategy {
virtual void Crypto() {
cout << "AES加密算法" << endl;
}
};
class DES : public Strategy {
virtual void Crypto() {
cout << "DES加密算法" << endl;
}
};
class Context {
public:
void setStrategy(Strategy* stratege) {
m_strategy = stratege;
}
void myOperator() {
m_strategy->Crypto();
}
private:
Strategy* m_strategy;
};
int main() {
Strategy* strategy = NULL;
strategy = new AES;
Context* context = new Context;
context->setStrategy(strategy);
context->myOperator();
std::cin.get();
return 0;
}