티스토리 뷰
동일한 목적의 알고리즘 선택을 적용하고자 할때 전략패턴을 사용하고자 합니다.
가령 스타크래프트에서 저글링을 선택 후 공격하고자 하때나 히드라 리스크를 선택하여 공격할때 해당 유닛의 공격방식도 달라집니다.
그리고 전략패턴의 경우 상태패턴과 거의 같습니다.
책을 봐도 구현방식같은 경우 거의 같은 것 같습니다.
단지 차이점이라면 상태패턴은 내부 상태에 의해 상태가 변경이 가능하다는 점입니다.
그렇지만 디자인패턴을 꼭 이 상황에 이렇게 넣겠다는 것보다는 적절하게 상황에 맞게 쓰는 게 좋을 듯 합니다.
아래는 간단한 다이어 그램입니다.
cBubbleSort와 cQuickSort는 cSortAlgoritm 인터페이스를 상속하여 각각의 Sort함수를 오버라이딩 합니다.
그리고 cIntegerArray클래스에서 해당 알고리즘을 쉽게 선택하여 사용 할수가 있습니다.
이렇게 함으로써 코드를 추가하여도 if~else나 switch~case문등을 넣지 않아도 되며, 기존 코드를 수정하지 않아도 됩니다.
class cSortAlgoritm { public: cSortAlgoritm() {} virtual void Sort() = 0; }; class cQuickSort : public cSortAlgoritm { public: virtual void Sort() { cout << "QuickSort \n"; delete this; } }; class cBubbleSort : public cSortAlgoritm { public: virtual void Sort() { cout << "BubbleSort \n"; delete this; } }; class cIntegerArray { public: void Sort(cSortAlgoritm* pSortAlgoritm ) { m_pSortAlgoritm = pSortAlgoritm; m_pSortAlgoritm->Sort(); } private: cSortAlgoritm *m_pSortAlgoritm; }; int main() { cIntegerArray *pSortAlgoritm = new cIntegerArray; pSortAlgoritm->Sort( new cQuickSort ); pSortAlgoritm->Sort( new cBubbleSort ); getch(); return 0; }