본문 바로가기
Design Patterns

[Design Patterns] Strategy Pattern

by matters_ 2021. 7. 30.

Strategy Pattern

알고리즘을 동적으로 선택할 수 있게 하는 디자인 패턴

behavioral software design pattern that enables selecting an algorithm at runtime.

Purpose

특정 행위를 하기 위해 교환할 수 있는 알고리즘을 정의할 수 있도록 합니다. 

Defines a set of encapsulated algorithms that can be swapped to carry out a specific behavior.

Use When

  • 행위기반적인 클래스들 간의 차이가 필요할 때
    The only difference between many related classes is their behavior.
  • 알고리즘의 다양한 버전, 변형이 필요할 때
    Multiple versions or variations of an algorithm are required.
  • 실행시간에 행위가 정의될 필요가 있을 때
    The behavior of a class should be defined at runtime.
  • 조건문 사용이 복잡하고 유지하기 어려울 때
    Conditional statements are complex and hard to maintain.

Example Code

#include <iostream>

class Strategy {
    public:
        Strategy() {}
        ~Strategy() {}
        virtual void Attack() = 0;
};

class Sword : public Strategy {
    protected:
        virtual void Attack() {
            printf("Sword attack!\n");
        }
};

class Gun : public Strategy {
    protected:
        virtual void Attack() {
            printf("Gun attack!\n");
        }
};

class Bazooka : public Strategy {
    protected:
        virtual void Attack() {
            printf("Bazooka attack!\n");
        }
};


class Character {
    private:
        Strategy *stg;
    public:
        Character () {stg = nullptr;}
        ~Character () {}

        void ChangeWeapon(Strategy *s) {
            if (this->stg != nullptr) {
                delete this->stg;
            }
            this->stg = s;
        }
        void Perform() {
            if (this->stg == nullptr) {
                printf("No Weapon\n");
                return;
            }
            this->stg->Attack();
        }
};

int main() {
    Character *ch = new Character();
    ch->Perform();

    ch->ChangeWeapon(new Sword());
    ch->Perform();

    ch->ChangeWeapon(new Gun());
    ch->Perform();

    ch->ChangeWeapon(new Bazooka());
    ch->Perform();
    return 0;
}

Output

Reference

https://en.wikipedia.org/wiki/Strategy_pattern

'Design Patterns' 카테고리의 다른 글

[Design Patterns] (Abstract) Factory Pattern  (0) 2021.08.06
[Design Patterns] Composite Pattern  (0) 2021.07.26

댓글