2013-02-25 5 views
2

C++에서 전략 패턴을 구현하고 싶지만 의심 스럽습니다. Alwyas의 전략 패턴 예제는 코드에 따르는 것입니다 (C# 참조). MainClass와 같은 클라이언트를 수정하여 구체적인 전략을 선택하는 것이 동적 인 방법입니다. 예를 들어, 전략 이름을 main 메소드의 args [] 매개 변수로 전달하십시오. 이 패턴의 속성을 수정하지 않고 어떻게 구현할 수 있습니까? 우리는 C++에 반사가없는전략 패턴 C++

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); 
    } 
    } 
} 
+0

이 언어는 무엇입니까? atleast 1 오타 및 여러 가지 구문 오류 .. C# 더 보이는? –

+0

@ KarthikT가 답한 것처럼, C++의 문자열에서 직접 할 수는 없지만 그의 대답은 한 가지 방법입니다. "Dependency Injection"은 동적 인 것들을 포함하여 모든 종류의 방법으로 이런 종류의 일을하는 프레임 워크를보기위한 좋은 검색 용어 일 것입니다. –

답변

1

, 즉 ..

이가 .. 내가 생각할 수있는 대안은 아래와 같이 공장 방법을 확인하는 것입니다 올바른 일을하는 데 필요한 개념이다
ISort* CreateSorter(SortType type) 
{ 
    switch (type){ 
    case QUICK_SORT: return new CQuickSorter(); 
    ... 
    } 
} 

클리너 코드에 enum을 사용하지만, 내 기본 사항을 이해할 수있는 한 문자열로 변경할 수 있습니다.

+0

C++ 로의 리플렉션을 기대합니다. http://root.cern .ch/drupal/content/c14 – Carl

+0

@carleeto 처음 본 것이지만, 다음과 같은 두 가지 표준이 2014 년과 2017 년에 계획되어 있으며, 2014 년은 2003 년과 비슷할 것으로 예상됩니다. 주로 버그 수정 및 사용성 개선 * C++에서 반영이 이루어질 것입니다. –

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 
}