"save"的设计模式
design pattern for "save"
我目前正在研究一种"保存"机制,该机制允许用户将他正在进行的项目保存在硬盘上。输出将是一个包含各种数据的XML文件
现在我们的项目结构即将改变,我们需要编写一个新的xml文件(创建一个新保存方法)
所以现在的挑战来了:保存时,我希望用户能够选择他将创建的文件格式(版本1(旧)或版本2(新))
现在有人能做到这一点吗?周围有合适的设计模式吗
备注:-我们保存的数据可以被视为不相关的块,因此用新块交换旧块实际上很容易。-这件事的全部目标是,当加载一个旧项目时,它应该是可读的。(我认为这可以通过标签来完成,并且在加载时只对标签做出反应?)
这听起来是Strategy模式的一个很好的应用程序。
您将创建一个抽象基类FileFormat
(策略接口),其中包含两个虚拟函数projectToXml
和xmlToProject
,它们应该将您的内部项目表示转换为XML,反之亦然。
然后创建两个实现子类FileFormatNew
和FileFormatLegacy
(这是具体的策略)。
然后,保存函数还需要一个FileFormat实例,并调用该对象的相应方法来进行数据转换。您的加载函数可以通过检查XML树来选择要使用的策略,以便告诉它是哪个版本
当你需要支持另一种文件格式时,你只需要创建一个新的类,它是FileFormat的子类。
意见交流后的补遗
当你有很多版本的差异很小,但你仍然想使用Strategy模式时,你可以让FileFormat由多种策略组成:CircleStragegy、RectangleStrategy、LineStrategy等。在这种情况下,我不会对不同版本的FileFormat使用不同的类。我会为每个版本创建一个静态工厂函数,它返回一个带有该版本中使用的Strategy对象的FileFormat。
FileFormat FileFormat::createVersion1_0() {
return new FileFormat(
new LineStrategyOld(),
new CircleStrategyOld(),
new RectangleStragegyOld()
);
}
FileFormat FileFormat::createVersion1_1() {
// the 1.1 version introduced the new way to save lines
return new FileFormat(
new LineStrategyNew(),
new CircleStrategyOld(),
new RectangleStragegyOld()
);
}
FileFormat FileFormat::createVersion1_2() {
// 1.2 uses the new format to save circles
return new FileFormat(
new LineStrategyNew(),
new CircleStrategyNew(),
new RectangleStragegyOld()
);
}
FileFormat FileFormat::createVersion1_3() {
// 1.3 uses a new format to save rectangles, but we realized that
// the new way to save lines wasn't that good after all, so we
// returned to the old way.
return new FileFormat(
new LineStrategyOld(),
new CircleStrategyNew(),
new RectangleStragegyNew()
);
}
注意:在实际代码中,策略类名当然会使用比"Old"answers"New"更多的描述性后缀。
- 派生类是否可以在抽象工厂设计模式中具有数据成员
- 资源管理设计模式
- 用于在回调中调用解析器的设计模式
- 设计帮助 - 为不同类型的消息处理通用接口的设计模式
- 在这种情况下我应该使用哪种设计模式
- C++中物体改变识别的设计模式?
- 确保所有构造函数调用相同的函数 c++ 设计模式
- 需要实例化不同类/对象并在启动时确定的硬件插槽的设计模式
- 设计模式,以避免不必要地添加抽象函数以适应新功能
- 工厂设计模式优化
- 使用C++模板的数据映射器设计模式
- 为什么以及如何使用原型设计模式
- 具有多个继承共享一个资源的对象 - 寻找良好的设计模式
- 在C++中创建观察器设计模式的好方法
- 现代C++在多大程度上消除了对设计模式的需求?
- 对于存储另一个类所需信息的类,例如其构造,是否有设计模式?
- 下面抽象工厂设计模式的实现是正确的吗
- sql记录集函数的状态设计模式
- 是否有可以处理方法调用依赖关系的设计模式?
- "save"的设计模式