I am trying to develop a game and I was having issues managing the creation and destruction of game objects and was suggested by several people to try using a factory pattern.
I went and read up on the factory pattern and I am trying to implement it and I have hit a roadblock.
// inside of EnemyGuy.h
#pragma once
#include "Entity.h"
#include "EntityFactory.h"
class EnemyGuy: public Entity {
public:
void update();
}
//inside of EnemyGuy.cpp
#include "EnemyGuy.h"
void EnemyGuy::update(){
if (you see player)
Entity* shotFired = EntityFactory::create("bullet", params);
}
// inside of EntityFactory.h
#pragma once
class Entity
#include "Bullet.h"
#include "EnemyGuy.h"
class EntityFactory{
public:
static Entity* create(const std::string passed, params);
}
// inside of EntityFactory.cpp
#include "EntityFactory.h"
static Entity* create(const std::string passed, params){
if (passed == "bullet")
return new Bullet(params);
if (passed == "enemyguy")
return new EnemyGuy(params);
}
I get a cyclic dependency error because the factory needs to include EnemyGuy so it can create instances of it and then EnemyGuy needs to include the factory so it can call the create() method.
Normally you would break a cyclic dependency with a forward declare but in this case a forward declare won’t do it.
How can I resolve this issue?
The factory header file doesn’t need to include it. Separate the declaration and the implementation and you’ll be fine.
EntityFactory.h:
EntityFactory.cpp:
The idea is that the factory header file and declaration never change, regardless of how many new options you add to it.