战略模式C++
Strategy Pattern C++
我想在C++中实现策略模式,但我有疑问。正如策略模式示例所示,下面是代码(在C#中(。我想修改客户端,即MainClass,这样选择的具体策略将是动态的。例如,通过主方法的args[]参数传递策略名称。在不修改此模式的属性的情况下,我将如何实现这一点?。
namespace StrategyPatterns
{
// Interface definition for a Sort algorithm
public interface ISort
{
void Sort(List<string> list)
}
// QuickSort implementation
public class CQuickSorter : ISort
{
void Sort(List<string> list)
{
// Here will come the actual imp
}
}
// BubbleSort
public class CBubbleSort : ISort
{
void Sort(List<string> list)
{
// The actual imp of the sort
}
}
public class Context
{
private ISort sorter;
public Context(ISort sorter)
{
// We pass the context the strategy to use
this.sorter = sorter;
}
public ISort Sorter
{
get{return sorter;)
}
}
public class MainClass
{
static void Main()
{
List<string> myList = new List<string>();
myList.Add("Hello world");
myList.Add("Another item");
Contexto cn = new Contexto(new CQuickSorter());
cn.Sorter.Sort(myList);
cn = new Contexto(new CBubbleSort());
cn.Sorter.Sort(myList);
}
}
}
我们在C++中没有反射,这是正确工作所需的概念。。我能想到的另一种选择是制作如下的工厂方法。。
ISort* CreateSorter(SortType type)
{
switch (type){
case QUICK_SORT: return new CQuickSorter();
...
}
}
我使用enum
来表示更干净的代码,但只要您能够理解我的基本观点,就可以将其更改为字符串。
我会给上下文类一个模板化的工厂函数setSorter
,并在内部处理分类器对象的整个生命周期。
class Interface { //this class and all sorting clases could be templated to be able to deal with sorting lists of different data types
std::unique_ptr<ISort> sorter_;
public:
Interface():sorter_(new CQuickSorter()){ //CQuickSorter is the default sorter
}
template<typename T>
setSorter(){ //one could also use perfect forwarding to pass arguments to T's constructor
sorter_.reset(new T());
}
void sort(std::list<string> &list){
sorter_->sort(list);
}
};
int main(){
std::list<int> li;
Interface cn;
cn.sort(li); //using a default sort
cn.setSorter<CBubbleSort>();
cn.sort(li); //using bubble sort
}
相关文章:
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 为什么在保护模式下继承升级不起作用
- 如何在全屏模式下(在OpenGL中)使背景透明
- 为什么使用__LINE_的代码在发布模式下在MSVC下编译,而不是在调试模式下
- 派生类是否可以在抽象工厂设计模式中具有数据成员
- 此模式的C++RegEx
- avrogencpp能为模式中的每种类型生成单独的头文件吗
- 使用可变模板的Broadcaster/Listener模式
- c++方法参数只能在linux的发布模式下自行更改
- 资源管理设计模式
- 使用 mod_gsoap 部署服务时,如何在 Gsoap 中更改 soap 上下文的模式?
- C++ 无法在字符数组中使用 for 循环打印字母模式
- 小字符串优化(调试与发布模式)
- 可视化C++:发布模式的运行时库作为'Multi-threaded Debug DLL'
- 如何设计具有不同类型的通知和观察器的观察者模式?
- 在C++的一系列数字中查找重复模式
- 是否允许使用带有"w+"模式的 freopen 进行标准设置?
- C++ 使用存储在动态数组中的文本文件中的数据查找模式
- С++ wxWidgets:代码架构,设计原则和模式
- 以只读模式打开数据库时SQLITE_CANTOPEN错误