首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >策略模式C++

策略模式C++
EN

Stack Overflow用户
提问于 2013-02-25 09:59:33
回答 2查看 2.3K关注 0票数 2

我想在C++中实现策略模式,但我有一个疑问。通常,策略模式的示例比下面的代码(在C#中)更好。我想修改客户端,即MainClass,这样选择具体的策略将是动态的方式。例如,通过main方法的args[]参数传递策略名称。我将如何在不修改此模式的属性的情况下实现此功能?

代码语言:javascript
复制
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);
    }
  }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-02-25 10:06:42

我们在C++中没有反射,这是你需要让它正确工作的概念。我能想到的另一种方法是创建一个工厂方法,如下所示。

代码语言:javascript
复制
ISort* CreateSorter(SortType type)
{
    switch (type){
    case QUICK_SORT: return new CQuickSorter();
    ...
    }
}

我使用enum来使代码更整洁,但您可以将其更改为字符串,只要您能够理解我的基本观点。

票数 1
EN

Stack Overflow用户

发布于 2013-12-12 04:20:47

我会给context类一个模板化的工厂函数setSorter,并在内部处理排序对象的整个生命周期。

代码语言:javascript
复制
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
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15059004

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档