策略模式是指定义一系列的算法,把它们一个个封装起来,并且使它们可相互替换。使得算法可独立于使用它的客户而变化。也就是说这些算法所完成的功能一样,对外的接口一样,只是各自实现上存在差异。用策略模式来封装算法,效果比较好
#include <iostream>
using namespace std;
//抽象接口
class Algorithm
{
public:
virtual void replace() = 0;
};
//算法1
class Algorithm1 : public Algorithm
{
public:
void replace()
{
cout << "this is Algorithm1" << endl;
}
};
//算法2
class Algorithm2 : public Algorithm
{
public:
void replace()
{
cout << "this is Algorithm2" << endl;
}
};
//算法3
class Algorithm3 : public Algorithm
{
public:
void replace()
{
cout << "this is Algorithm3" << endl;
}
};
enum AlgorithmFlag
{
A1,
A2,
A3
};
//计算
class Compute
{
public:
Compute(enum AlgorithmFlag flag)
{
if(flag == A1)
_algorithm = new Algorithm1;
else if(flag == A2)
_algorithm = new Algorithm2;
else if(flag == A3)
_algorithm = new Algorithm3;
else
_algorithm = NULL;
}
~Compute()
{
if(_algorithm)
delete _algorithm;
}
void replace()
{
_algorithm->replace();
}
private:
Algorithm *_algorithm;
};
int main()
{
Compute compute(A1);
compute.replace();
return 0;
}