클라이언트 객체에서 서로 교환가능한 구현(전략)들을 의존성 없이 변경 가능하도록 하는 패턴
#include <iostream>
using namespace std;
class Strategy {
public:
Strategy() {}
~Strategy() {}
virtual void execute() = 0;
};
class A_strategy : public Strategy {
protected:
virtual void execute() {
printf("A strategy!\n");
}
};
class B_strategy : public Strategy {
protected:
virtual void execute() {
printf("B strategy!\n");
}
};
class Character {
public:
Character() {}
~Character() {}
void ChangeStrategy(Strategy *s) {
if (this->stg != nullptr) {
delete this->stg;
}
this->stg = s;
}
void Perform() {
if (this->stg == nullptr) {
printf("no strategy!\n");
return;
}
this->stg->execute();
}
private:
Strategy *stg;
};
int main() {
Character *ch = new Character();
ch->Perform();
ch->ChangeStrategy(new A_strategy());
ch->Perform();
ch->ChangeStrategy(new B_strategy());
ch->Perform();
return 0;
}
| cs |
ch객체에서 A라는 전략을 수행한 후 전략을 바꾸어 B라는 전략을 수행하고있다.
(18.11.26) - python 버전 추가
class Strategy:
_name = None
def action(self):
pass
""" sub class """
class FirstStrategy(Strategy):
def __init__(self, name):
self._name = name
def action(self):
print(self._name,' First algorithm start!')
""" sub class """
class SecondStrategy(Strategy):
def __init__(self, name):
self._name = name
def action(self):
print(self._name,' Second algorithm start!')
class Unit:
_strategy = Strategy()
_name = None
def __init__(self, name):
self._name = name
def ChangeStrategy(self, strg):
self._strategy = strg
def Show(self):
print('my name is ',self._name)
self._strategy.action()
print()
jihoon = Unit('JiHoon')
jihoon.ChangeStrategy(FirstStrategy('fly'))
jihoon.Show()
jihoon.ChangeStrategy(SecondStrategy('kill'))
jihoon.Show()
| cs |
파이썬 버전도 기본 logic은 동일하다.
댓글 없음:
댓글 쓰기