策略模式(strategy)定义了一个算法家族,这个算法家族封装了一系列的算法,但是这些算法之间是相互可以替换的。策略模式让算法的变化和它们调用者的变化分离开来了。
UML图如下:
主要包括:
- Strategy:声明了一个对所有算法而言通用的接口类,下面的Contex类使用这个接口来调用一个一个具体的Stragety的算法。
- ConcreteStrategy:使用Strategy这个接口具体化的算法类
- Context:通过一个指向具体的Strategy的指针来操作这个具体的Strategy对象。
下面是根据上面的UML图编写的C++代码:
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
class Strategy
{
public:
virtual void algorithmInterface()=0;
};
class ConcreteStrategyA:public Strategy
{
public:
void algorithmInterface()
{
std::cout<<"ConcreteStrategyA::algorithmInterface()"<<std::endl;
}
};
class ConcreteStrategyB:public Strategy
{
public:
void algorithmInterface()
{
std::cout<<"ConcreteStrategyB::algorithmInterface()"<<std::endl;
}
};
class ConcreteStrategyC:public Strategy
{
public:
void algorithmInterface()
{
std::cout<<"ConcreteStrategyC::algorithmInterface()"<<std::endl;
}
};
class Context
{
public:
void setStrategy(Strategy * s)
{
strategy=s;
}
void contextInterface()
{
strategy->algorithmInterface();
}
private:
Strategy* strategy;
};
int main()
{
Context context;
Strategy *sa=new ConcreteStrategyA();
Strategy *sb=new ConcreteStrategyB();
Strategy *sc=new ConcreteStrategyC();
context.setStrategy(sa);
context.contextInterface();
context.setStrategy(sb);
context.contextInterface();
context.setStrategy(sc);
context.contextInterface();
delete sa;
delete sb;
delete sc;
return 0;
}
执行结果如下:
一个具体的例子:
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <string>
#include <list>
#include <algorithm>
using namespace std;
/*一个具体的策略模式的例子
* Strategy为SortStrategy
* ConcreteStrategy为QuickSort,ShellSort,MergeSort
* Contex为SortedList
* */
//所有排序类的父类
class SortStrategy
{
public:
virtual void sort(list<string>& lists)=0;
};
class QuickSort:public SortStrategy
{
public:
void sort(list<string>& lists)
{
std::cout<<"QuickSort:sort"<<std::endl;
}
};
class ShellSort:public SortStrategy
{
public:
void sort(list<string>& lists)
{
std::cout<<"ShellSort:sort"<<std::endl;
}
};
class MergeSort:public SortStrategy
{
public:
void sort(list<string>& lists)
{
std::cout<<"Merge:sort"<<std::endl;
}
};
class SortList
{
public:
void sort()
{
sortStrategy->sort(lists);
print();
}
void setSortStrategy(SortStrategy * s)
{
sortStrategy=s;
}
void add(string str)
{
lists.push_back(str);
}
void print()
{
list<string>::iterator iter;
for(iter=lists.begin();iter!=lists.end();iter++)
{
std::cout<<*iter<<std::endl;
}
}
private:
list<string> lists;
SortStrategy * sortStrategy;
};
int main()
{
SortList sortList;
sortList.add("allan");
sortList.add("john");
sortList.add("harrison");
QuickSort *qs=new QuickSort();
ShellSort *ss=new ShellSort();
MergeSort *ms=new MergeSort();
sortList.setSortStrategy(qs);
sortList.sort();
sortList.setSortStrategy(ss);
sortList.sort();
sortList.setSortStrategy(ms);
sortList.sort();
delete qs;
delete ss;
delete ms;
return 0;
}
执行结果:(在具体的地方加上相应的排序函数即可)