【问题标题】:Internal vs External Mapping of IDs to file paths from function perspective从函数的角度来看,ID 到文件路径的内部与外部映射
【发布时间】:2020-07-10 17:03:34
【问题描述】:

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

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

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

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

  1. loadTexture() 接受TextureID

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

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

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

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

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

我认为第一种方法更方便,但它将TextureManager 耦合到mapIdToFilepath(),因为它在内部执行TextureID 到文件路径的转换。

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

【问题讨论】:

  • “从架构的角度来看,最好的方法是什么?” - 这是 100% 基于意见的。问 100 位不同的程序员,你会得到许多不同的答案。
  • @JesperJuhl 谢谢。我已正确编辑问题以更好地表达我的意图。

标签: c++ architecture sfml clean-architecture


【解决方案1】:

我假设,从广义上讲,您正在寻找像资产管理器这样的工具来仅加载您的资产(无论是纹理、声音或字体)一次并在任何地方使用它们。你可以使用我很久以前使用的东西。创建一个 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;
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-12
    • 2012-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-18
    • 2021-10-15
    相关资源
    最近更新 更多