프로그래밍/GoF
[행동 패턴] - 전략(Strategy)
MAKGA
2022. 1. 8. 16:37
320x100
구조
#pragma once
#include <iostream>
#include <set>
#include <string>
class Strategy
{
public:
virtual int algorithmInterface(int a, int b) = 0;
};
class Context
{
private:
Strategy* strategy_;
public:
Context(Strategy* strategy)
{
strategy_ = strategy;
}
void changeStrategy(Strategy* strategy)
{
strategy_ = strategy;
}
void contextInterface()
{
std::cout << strategy_->algorithmInterface(5, 5) << std::endl;
}
};
class StrategyA : public Strategy {
public:
int algorithmInterface(int a, int b) override
{
return a * b;
}
};
class StrategyB : public Strategy
{
int algorithmInterface(int a, int b) override
{
return a + b;
}
};
class StrategyC : public Strategy
{
int algorithmInterface(int a, int b) override
{
return a - b;
}
};
사용
int main()
{
StrategyA* strategyA = new StrategyA;
StrategyB* strategyB = new StrategyB;
StrategyC* strategyC = new StrategyC;
Context* context = new Context(strategyA);
context->contextInterface();
context->changeStrategy(strategyB);
context->contextInterface();
context->changeStrategy(strategyC);
context->contextInterface();
system("pause");
return 0;
}
동일 계열의 알고리즘을 객체화하여 동일한 인터페이스(Strategy의 algorithmInterface())를 통해 다양한 알고리즘을 사용할 수 있게 하는 패턴이다.
알고리즘을 사용하는 객체(Context)는 전략 객체(Strategy의 파생 클래스)를 교체해 동일한 계열의 다양한 알고리즘을 선택할 수 있다.
320x100