c++ - 从函数的角度来看,ID 到文件路径的内部与外部映射
问题描述
一个可以与多个对象sf::Sprite
共享同一个对象,所以我想设计一个纹理管理器来多次使用不同的纹理。sf::Texture
sf::Sprite
我正在使用标识符来引用纹理。ATextureID
将纹理映射到与包含该纹理的文件对应的文件路径:
std::filesystem::path mapIdToFilepath(TextureID id);
在TextureManager
我想要一个成员函数loadTexture()
中,我在想:
接受
loadTexture()
一个TextureID
:sf::Texture& TextureManager::loadTexture(TextureID id);
然后,该函数必须通过调用在内部将标识符
TextureID
转换为纹理文件路径mapIdToFilepath()
。或接受纹理的文件路径作为参数:
sf::Texture& TextureManager::loadTexture(std::filesystem::path filepath);
调用此函数的客户端代码必须将标识符
TextureID
转换为纹理文件路径。但是,此函数不必知道 的存在,mapIdToFilepath
因为映射是在外部完成的。
我认为第一种方法更方便,但它耦合TextureManager
,mapIdToFilepath()
因为它在内部TextureID
进行文件路径转换。
从架构的角度来看,在考虑这两种不同的方法时,我应该牢记哪些方面?
解决方案
我假设,从广义上讲,您正在寻找像资产管理器这样的东西来加载您的资产(无论是纹理、声音还是字体)一次并在任何地方使用它们。你可以使用我很久以前使用的东西。创建一个 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;
}
不要按原样使用代码,因为您需要为加载失败或地图的键值不正确添加条件。如果您需要其他内容或我的回答有误,请告诉我。谢谢你。:)
推荐阅读
- python - 如何测量程序以不考虑处理器速度的标准化方式运行所需的时间?
- flutter - 如何防止在父小部件 GestureDetector 上触发 onTapDown?
- python - 带有 C 的 Arduino 不接收 Python 输入
- functional-programming - 将随机索引生成到数组中的最佳方法?
- perl - S3 签名与 Amazon::S3 perl 不匹配
- ruby-on-rails - 如何在 Rails 5 中运行默认的 rake 任务?
- scala - 一些简单的scala代码中的奇怪减速
- laravel - 使用 group by 和 where 的 Laravel 查询不起作用
- html - 空 div 不可见
- android - 创建具有圆角和阴影和自定义图像的 Android 形状