我不得不说,我总是尽量保持代码简单美观,主要是尽可能使用设计模式。另外,令我印象深刻的是我在互联网上没有找到与此相关的任何内容(除了简单且非常模糊的示例,主要是在使用 json 的 javascript 中)。
场景是:我必须从一个文件中解析/构建具体对象,该文件的内容可能是 XML、JSON 和/或其他格式。这是一个例子:
具体对象:
// Contains the common states for the entities
struct EntityModel
{
int hp;
int level;
int armor;
int speed;
// Other attributes...
};
class Entity
{
// Stuff (protected/public/private attributes and functions/methods)
private:
EntityModel* m_model; // Pointer to the model used (flyweight)
// Other attributes...
}
文件(在本例中为 XML):
<entity name="Skeleton" class="Undead">
<attributes>
<hp value="150" />
<level value="10" />
<armor value="75" />
<speed value="15" />
<width value="32" />
<height value="32" />
<experience value="372" />
<texture value="skeleton.png" />
<intelligence value="skeleton.script" />
</attributes>
<restistances>
<resist type="Shock" value="30" />
<resist type="Fire" value="10" />
</resistances>
<attacks>
<spell name="Blizzard" mp="50" damage="130" distance="0" />
<spell name="Fireball" mp="30" damage="100" distance="0" />
</attacks>
<loot>
<drop item="Gold Coin" min="30" max="50" probability="1" />
<drop item="Ruby" min="0" max="2" probability="0.7" />
<drop item="Enchanted Sword" probability="0.25" />
</loot>
</entity>
这是实体模型与其文件之间关系的示例。还会有其他对象必须能够从它们的文件中解析/构建/创建。
有些人可能会说在这种情况下设计模式并不是真正必要的,正如我在一些实现中看到的那样,尽管我确实相信有一个。整个实体创建系统涉及抽象工厂、池和享元模式(向工厂请求 createEntity 调用,它将查看是否已创建享元模型并将其缓存在池中或创建并缓存新模型)。
所以,问题是:有什么合适的方法可以做到这一点吗?哪个?
正如我所说的,我将基于这个案例的答案并适应其他对象创建。换句话说,我需要一个通用的答案。
如果这篇文章缺少一些信息,或者在错误的部分,请原谅我,因为这是我在这里的第一篇文章。
提前致谢。
最佳答案
试试 Boost Serialization Library .它有 xml、二进制和文本保存格式。它不太复杂并且有很好的文档。
关于c++ - 从文件构建具体对象。有没有适合这个的设计模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33137951/