首页 > 解决方案 > 从函数的角度来看,ID 到文件路径的内部与外部映射

问题描述

一个可以与多个对象sf::Sprite共享同一个对象,所以我想设计一个纹理管理器来多次使用不同的纹理。sf::Texturesf::Sprite

我正在使用标识符来引用纹理。ATextureID将纹理映射到与包含该纹理的文件对应的文件路径:

std::filesystem::path mapIdToFilepath(TextureID id);

TextureManager我想要一个成员函数loadTexture()中,我在想:

  1. 接受loadTexture()一个TextureID

    sf::Texture& TextureManager::loadTexture(TextureID id);
    

    然后,该函数必须通过调用在内部将标识符TextureID转换为纹理文件路径mapIdToFilepath()

  2. 或接受纹理的文件路径作为参数:

    sf::Texture& TextureManager::loadTexture(std::filesystem::path filepath);
    

    调用此函数的客户端代码必须将标识符TextureID转换为纹理文件路径。但是,此函数不必知道 的存在,mapIdToFilepath因为映射是在外部完成的。

我认为第一种方法更方便,但它耦合TextureManagermapIdToFilepath()因为它在内部TextureID进行文件路径转换。

架构的角度来看,在考虑这两种不同的方法时,我应该牢记哪些方面?

标签: c++architecturesfmlclean-architecture

解决方案


我假设,从广义上讲,您正在寻找像资产管理器这样的东西来加载您的资产(无论是纹理、声音还是字体)一次并在任何地方使用它们。你可以使用我很久以前使用的东西。创建一个 Asset Manager 类,它将在地图中包含您的纹理。像这样的东西:

class TexManager
{
public:

    TexManager* tex()  //to access your assets without creating multiple instances of this class
    {
         static Texmanager texMan;
         return &texMan;
    }

    void loadTexture(std::string name, std::string filepath) //to load textures
    { 
         sf::Texture tmp;
         tmp.loadFromFile(filepath);
         texMap.insert(std::make_pair(name, tmp));
    }

    sf::Texture& getTexture(st::string name) //to retrieve textures
    { 
         return texMap.at(name);
    }

private:
    std::map<std::string, sf::Texture> texMap;
}

不要按原样使用代码,因为您需要为加载失败或地图的键值不正确添加条件。如果您需要其他内容或我的回答有误,请告诉我。谢谢你。:)


推荐阅读