#pragma once
/*=================================
Factory Pattern
=================================*/
/*
객체를 생성하는 인터페이스를 정의하고 구체적인 객체는 서브클래스에 생성하도록 하는 패턴
장점
ㄴ 유연성 : 객체 생성 로직을 중앙 집중화 시킨다.
ㄴ 추상화 : 구체적인 클래스에 의존하지 않아 다양한 구현체에 적용 가능
ㄴ 확장성: 기존 코드에 영향을 주지 않고 새로운 팩토리 클래스를 확장할 수 있다.
단점
ㄴ 복잡성 : 작은 프로젝트에서는 팩토리 클래스로 인해 불필요한 복잡성이 생길 수 있음.
ㄴ 가독성 : 객체 생성을 위한 추상화가 많아져 가독성을 떨어뜨릴 수 있음.
*/
enum class EnemyType : __int16
{
GOBLIN,
ORC
};
class Enemy
{
public:
Enemy() {}
Enemy(int hp, int mp)
: _hp(hp)
, _mp(mp)
{}
virtual ~Enemy() {}
// 공통적으로 사용할 순수 가상 함수
virtual void attack() = 0;
void setHp(int hp)
{
_hp = hp;
}
int getHp() const
{
return _hp;
}
void setMp(int mp)
{
_mp = mp;
}
int getMp() const
{
return _mp;
}
private:
int _hp = 0;
int _mp = 0;
};
class Goblin : public Enemy
{
public:
Goblin() {}
Goblin(int hp, int mp)
: Enemy(hp, mp)
{}
void attack() override
{
cout << "Goblin Attack" << endl;
}
};
class Orc : public Enemy
{
public:
Orc() {}
Orc(int hp, int mp) : Enemy(hp, mp) {}
void attack() override
{
cout << "Orc Attack" << endl;
}
};
EnemyFactory에서 객체 생성
#pragma once
#include "Enemy.h"
/*
여러 Enemy들을 팩토리에서 생성
*/
class EnemyFactory
{
public:
static unique_ptr<Enemy> createEnemy(const EnemyType type)
{
switch (type)
{
case EnemyType::GOBLIN:
return make_unique<Goblin>();
case EnemyType::ORC:
return make_unique<Orc>();
default:
return nullptr;
}
}
};