0

我正在尝试开发游戏,但在管理游戏对象的创建和销毁时遇到问题,并且有几个人建议尝试使用工厂模式。我去阅读了工厂模式,我正在尝试实施它,但遇到了障碍。

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

我收到一个循环依赖错误,因为工厂需要包含 EnemyGuy 以便它可以创建它的实例,然后 EnemyGuy 需要包含工厂以便它可以调用 create() 方法。

通常你会用前向声明打破循环依赖,但在这种情况下,前向声明不会这样做。我该如何解决这个问题?

4

1 回答 1

2

工厂头文件不需要包含它。将声明和实现分开,你会没事的。

实体工厂.h:

class Entity

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

实体工厂.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);
 }

这个想法是工厂头文件和声明永远不会改变,无论您添加多少新选项。

于 2012-06-14T22:22:16.410 回答