策略模式:它定义了算法家族,分别封装起来,让他们之间可以互相替换,此模式让算法变化,不会影响到使用算法的客户。
#include <iostream>
using namespace std;
class Strategy
{
public:
virtual void algorithm(){};
};
class StrategyA:public Strategy
{
public:
void algorithm()
{
printf("a");
}
};
class StrategyB:public Strategy
{
public:
void algorithm()
{
printf("b");
}
};
class Context
{
Strategy* strategy;
public:
Context(Strategy* strategy)
{
this->strategy=strategy;
}
void algorithm()
{
strategy->algorithm();
}
};
int main(int argc, const char * argv[])
{
Context* context=new Context(new StrategyA());
context->algorithm();
Context* context2=new Context(new StrategyB());
context2->algorithm();
}