策略模式
策略模式是指提供接口,让用户使用可替换的算法。
enum ALG {first, second, third}; //标签
//抽象接口
class Algorithm
{
public:
virtual void alg() = 0;
};
//三种具体的替换算法
class Algorithm1 : public Algorithm
{
public:
void alg() { cout << "Algorithm1" << endl; }
};
class Algorithm2 : public Algorithm
{
public:
void alg() { cout << "Algorithm2" << endl; }
};
class Algorithm3 : public Algorithm
{
public:
void alg() { cout << "Algorithm3" << endl; }
};
class User
{
private:
Algorithm *m_al;
public:
User(enum ALG a)
{
if(a == first)
m_al = new Algorithm1();
else if(a == second)
m_al = new Algorithm2();
else if(a == third)
m_al = new Algorithm3();
else
m_al = NULL;
}
~User() { delete m_ra; }
void alg() { m_ra->alg(); }
};
int main()
{
Cache cache(first); //指定算法标签
cache.Replace();
return 0;
}
这里使用标签来区分不同的算法,可以看出这么做会难以进行扩展。
使用函数指针和匿名函数会对策略模式有很大的帮助,举个例子:
struct Info
{
int a;
int b;
int c;
};
template <class L>
class Vector
{
public:
template <class T>
void sort(T t)
{
int i, j;
for (i = 0; i < InfoList.size(); i++)
for (j = 1; j < InfoList.size() - i; j++)
if (t(InfoList[j - 1],InfoList[j]))//依据用户提供的算法进行比较
std::swap(InfoList[j - 1], InfoList[j]);
}
private:
vector<L> InfoList;
};
int main()
{
Vector<Info> l;
l.sort([](Info x,Info y){if(x.a>y.a)return 1;else return 0;});
}
在这个例子中我们遇到了一个’复杂’的数据-由三个int组成的结构体,我们不知道如何对其进行排序,所以我们的sort函数提供了一个参数,用于接受比较函数,在例子中提供的函数依据结构体中的a值进行比较,那么sort就会依据这个算法进行排序。