"save"的设计模式

design pattern for "save"

本文关键字:设计模式 save      更新时间:2023-10-16

我目前正在研究一种"保存"机制,该机制允许用户将他正在进行的项目保存在硬盘上。输出将是一个包含各种数据的XML文件
现在我们的项目结构即将改变,我们需要编写一个新的xml文件(创建一个新保存方法)
所以现在的挑战来了:保存时,我希望用户能够选择他将创建的文件格式(版本1(旧)或版本2(新))
现在有人能做到这一点吗?周围有合适的设计模式吗
备注:-我们保存的数据可以被视为不相关的块,因此用新块交换旧块实际上很容易。-这件事的全部目标是,当加载一个旧项目时,它应该是可读的。(我认为这可以通过标签来完成,并且在加载时只对标签做出反应?)

这听起来是Strategy模式的一个很好的应用程序。

您将创建一个抽象基类FileFormat(策略接口),其中包含两个虚拟函数projectToXmlxmlToProject,它们应该将您的内部项目表示转换为XML,反之亦然。

然后创建两个实现子类FileFormatNewFileFormatLegacy(这是具体的策略)。

然后,保存函数还需要一个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"更多的描述性后缀。