2

戦略パターンを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);
    }
  }
}
4

2 に答える 2

1

C ++には反映されていません。これは、これを正しく機能させるために必要な概念です。私が考えることができる代替案は、以下のようにファクトリメソッドを作成することです。

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

私はenumよりクリーンなコードを使用していますが、私の基本的なポイントを理解できれば、それを文字列に変更できます。

于 2013-02-25T02:06:41.860 に答える
0

コンテキストクラスにテンプレート化されたファクトリ関数を与え、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
}
于 2013-12-11T20:20:47.303 に答える