【问题标题】:Strategy Pattern C++策略模式 C++
【发布时间】:2013-12-12 04:20:47
【问题描述】:

我想在 C++ 中实现策略模式,但我有疑问。 Alwyas 策略模式示例比遵循代码(在 C# 中)。我想修改客户端,即 MainClass,以便选择具体的策略将是动态的方式。 例如,通过 main 方法的 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);
    }
  }
}

【问题讨论】:

  • 这应该是哪种语言?至少 1 个拼写错误和几个语法错误.. 看起来更像 C#?
  • 正如@KarthikT 回答的那样,您不能直接从 C++ 中的字符串执行此操作,他的回答是一种方法。 “依赖注入”可能是一个很好的搜索词,可以看到以各种方式(包括一些动态的)做这类事情的框架。

标签: c++ design-patterns


【解决方案1】:

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

ISort* CreateSorter(SortType type)
{
    switch (type){
    case QUICK_SORT: return new CQuickSorter();
    ...
    }
}

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

【讨论】:

  • @carleeto 这是我第一次看到它,但我认为像 这样的声明接下来的两个标准计划在 2014 年和 2017 年,2014 年有点像 2003 年:主要是错误修复和可用性改进。 反射将出现在 C++17 中。
【解决方案2】:

我会给上下文类一个模板化的工厂函数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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-15
    • 1970-01-01
    相关资源
    最近更新 更多