上面是百度百科的图,多半它也是盗版来的,也不知道原作者是谁,请大家别再我这里复制这图哈。
策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。
//Filename: strategy.h
//Author: He.Mark.Qinglong
//说明: 除了这个模式是用在算法层面,怎么觉得这个和桥接模式差不多呢?还是STL的模版算法实现的策略模式靠谱点
#include <iostream>
class Strategy{
public:
virtual void AlgorithmInterface() = 0;
virtual ~Strategy(){}
};
class ConcreateStratA: public Strategy{
public:
virtual void AlgorithmInterface(){
std::cout<< "策略A" <<std::endl;
}
~ConcreateStratA(){}
};
class ConcreateStratB: public Strategy{
public:
virtual void AlgorithmInterface(){
std::cout<< "策略B" <<std::endl;
}
~ConcreateStratB(){}
};
class ConcreateStratC: public Strategy{
public:
virtual void AlgorithmInterface(){
std::cout<< "策略C" <<std::endl;
}
~ConcreateStratC(){}
};
class Context{
private:
Strategy *_stg;
public:
Context(Strategy *stg){
this->_stg = stg;
}
void contextInterface(){
this->_stg->AlgorithmInterface();
}
};
测试用例:
#include "strategy.h"
int main(){
auto context = new Context(new ConcreateStratA);
context->contextInterface();
delete context;
context = new Context(new ConcreateStratC);
context->contextInterface();
delete context;
context = new Context(new ConcreateStratB);
context->contextInterface();
delete context;
return 0;
}