공유되는 정보가 있다면 몇 개의 클래스 만으로 수백 개의 하위 클래스를 표현할 수 있다.
#include <iostream>
using namespace std;
class Breed {
public:
Monster* newMonster() {
return new Monster(*this);
}
Breed(Breed* parent, int health, const char* attack) : parent_(parent), health_(health), attack_(attack) {}
int GetHealth() {
//오버라이딩
if (health_ != 0 || parent_ == NULL)
return health_;
return parent_->GetHealth();
}
const char* GetAttack() {
//오버라이딩
if (attack_ != NULL || parent_ == NULL)
return attack_;
return parent_->GetAttack();
}
private:
Breed* parent_;
int health_; //초기 체력
const char* attack_;
};
class Monster {
friend class Breed;
public:
Breed& getBreed() {return breed_;}
const char* GetAttack() {
if(heath_<LOW_HEALTH)
{
return "몬스터가 공격할 힘이 없다";
}
return breed_.GetAttack();
}
private:
Monster(Breed& breed):health_(breed.GetHealth()), breed_(breed){}
int health_; //현재 체력
Breed& breed_;
};
int main() {
//체력과 공격문구만으로 몬스터 종류를 특정한다.
Breed ParentBreed(NULL, 100, "발록이 공격한다");
Breed childBreed(&ParentBreed, 100, "주니어발록이 공격한다");
Monster* monster = childBreed.newMonster();
}