c++ - C++库的可维护性

标签 c++ properties entity

我正在用 C++ 创建一个库,目的是在未来的应用程序(游戏)中使用它。我决定使用 Entity-Property 设计,其中可以通过向其附加各种属性来扩展基本实体。属性都是基类 GameProperty 的派生类,该类允许将它们存储在多态指针的单个 vector 中,该 vector 是 GameEntity 类的成员。我有一个 EntityManager 类,它根据可以从文件加载的 EntityTemplate,通过将正确的属性集附加到它们来创建专门的实体。

这就是问题所在:我希望能够轻松创建和添加新属性以满足给定项目的需要。但是每个新属性都不能简单地扩展 GameProperty,它需要尽可能无缝地集成到 EntityManager 中。 EntityManager 需要诸如“GraphicsProperty”、“InputProperty”等字符串,然后根据这些字符串选择要附加到新创建的实体的属性。我如何构建 Property 和 EntityManager 类,以便不需要为我编写的每个新 Property 添加特定于类型的代码到 EntityManager?

考虑下面的例子:

class GameProperty
{
    virtual void Update() = 0;
};

class GraphicsProperty : public GameProperty
{
    void Update();
};

class InputProperty : public GameProperty
{
    void Update();
};

class GameEntity
{
public:
    void AttachProperty(shared_ptr<GameProperty> newProperty)
    {
        properties.push_back(newProperty);
    };

    vector<shared_ptr<GameProperty>> properties;
};

class EntityTemplate
{
public:
    vector<string> properties;
};

class EntityManager
{
public:

std::shared_ptr<GameEntity>
EntityManager::CreateEntityFromTemplate(shared_ptr<EntityTemplate> entityTemplate)
{
    std::shared_ptr<GameEntity> newEntity = make_shared<GameEntity>();

    for each(string propertyName in entityTemplate->properties)
    {
        if(propertyName == "GraphicsProperty")
        {
            shared_ptr<GraphicsProperty> gProperty = make_shared<Graphics::GraphicsProperty>();
            newEntity->AttachProperty(gProperty);
        }
        else if(propertyName == "InputProperty")
        {
            shared_ptr<Input::InputProperty> iProperty = make_shared<Input::InputProperty>();
            newEntity->AttachProperty(iProperty);
        }
    }
};

};

上面没有看到从 XML 文件创建 EntityTemplate 对象的 EntityLoader。

最佳答案

您可以注册所有属性以构建属性工厂数组,并使用实体管理器中的工厂来创建它们,例如

class GamePropertyFactoryBase
{
public:
  virtual GameProperty *Create() const=0;
};

template<class T>
class GamePropertyFactory: public GamePropertyFactoryBase
{
public:
  virtual GameProperty *Create() const {return new T;}
};

typedef std::pair<const GamePropertyFactoryBase*, const char*> FactoryEntry_t;
std::vector<FactoryEntry_t> s_propertyFactories;

template<class T>
void RegisterProperty(const char *name_)
{
  static const GamePropertyFactory<T> s_factory;
  s_propertyFactories.push_back(FactoryEntry_t(&s_factory, name_));
}

void RegisterEntities()
{
  // register all properties here
  RegisterProperty<GraphicsProperty>("GraphicsProperty");
};

然后在 EntityManager 中从数组中搜索名称并调用:

GameProperty *prop=it->first->Create();

关于c++ - C++库的可维护性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24311166/

相关文章:

c# - linq lambda 多组连接

doctrine-orm - 使用 Doctrine 2 的 UniqueEntity

c++ - 折叠表达式 () 在哪里?

iphone - UIButton.layer.cornerRadius 不存在?

C# 在 setter 方法上添加验证

John Resig 的 Javascript Array.remove() - 为什么它在 for-in 语句中枚举?

java - JPA的内部运作

c++ - 如何参数化迭代器方向?

c++ - 链接错误 stdc++

c++ - 在使用 fwrite 创建图像后交换字节