0

게임을 개발하려고하는데 게임 오브젝트의 생성 및 파괴를 관리하는 데 문제가있어 여러 사람들이 공장 패턴을 사용해 보라고 제안했습니다. 공장 패턴을 읽고 그 패턴을 구현하려고하는데로드 블록을 쳤습니다. 그것의 인스턴스를 만들 수 있도록 공장 EnemyGuy을 포함해야하고 EnemyGuy이는 create() 메소드를 호출 할 수 있도록 공장을 포함해야하기 때문에 공장 패턴의 원형 종속성 깨기

// 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); 
} 

나는 순환 종속성 오류가 발생합니다.

일반적으로 forward 선언문을 사용하여 주기적 종속성을 깨뜨리지 만,이 경우 forward 선언은 수행하지 않습니다. 이 문제를 어떻게 해결할 수 있습니까?

답변

2

팩토리 헤더 파일에 포함 할 필요가 없습니다. 선언과 구현을 분리하면 괜찮을 것입니다.

EntityFactory.h :

class Entity 

class EntityFactory{ public: 
    static Entity* create(const std::string passed, params); 
} 

EntityFactory.cpp :

#include "EntityFactory.h" 
#include "Bullet.h" 
#include "EnemyGuy.h" 

Entity* EntityFactory::create(const std::string passed, params){ 
    if (passed == "bullet") 
     return new Bullet(params); 
    if (passed == "enemyguy") 
     return new EnemyGuy(params); 
} 

아이디어는 그 공장 헤더 파일 선언에 관계없이 추가 얼마나 많은 새로운 옵션의 결코 변화, 그것.

+0

감사합니다. – user1438585