策略模式
策略模式针对一组算法,将每一个算法封装到具有共同接口的独立的类中,从而使得它们可以相互替换。策略模式使得 算法可以在不影响到客户端的情况下发生变化。策略模式把行为和环境分开。环境类负责维持和查询行为类,各种算法在具体的策略类中提供 。由于算法和环境独立开来,算法的增减,修改都不会影响到环境和客户端。
跟不同类型的MM约会,要用不同的策略,有的请电影比较好,有的则去吃小吃效果不错,有的去海边浪漫最合适,虽说方法不同,但是最后的目的却是
#include <iostream>
using namespace std;
class Strategy{
public:
virtual ~Strategy(){}
virtual void crypt()=0;
};
class AES : public Strategy{
public:
virtual void crypt(){
std::cout << "AES crypt" << std::endl;
}
};
class DES : public Strategy{
public:
virtual void crypt(){
std::cout << "DES crypt" << std::endl;
}
};
class Context
{
public:
void setStrategy(Strategy *strategy){
this->strategy=strategy;
}
void operate(){
this->strategy->crypt();
}
private:
Strategy *strategy;
};
int main()
{
Strategy *des = new DES();
des->crypt();
Context *context = new Context();
context->setStrategy(des);
return 0;
}