我有现有的Calss MyParser,它有解析XML并获取特定值的方法,目前它使用XPath来执行此操作。
class MyParser
{
public Parse(xmldoc) { ... }
public GetProperties(...) { ... }
public Validate(...) { .... }
}
用法:
MyParser myParser = new MyParser();
myParser.Parse();
....
MyParser.GetProperties(...);
....
MyPaser.Validate(...);
当时设计的类没有为XML定义模式。此代码已在产品中。
现在,已经为此XML定义了产品模式的更高版本,并且XML结构也发生了变化。所以在当前版本的产品中我决定使用Schema类(用XSD生成的类)来解析这个XML,
因此,产品应该支持逻辑,这意味着它应该支持解析XML类型。我不想更改实例化和使用类的代码。为了识别哪个XML已传递给Myparser,在较新的模式中引入了一个标记。
我可以通过添加如下所示的条件来更改现有的解析方法
我不想做这种结构化编程方式。是否有任何定义良好的设计模式以OOPS方式解决此问题?
// code get version info from XML
if(version exists and version == 2)
{
// existing code
}
else
{
// new code.
}
答案 0 :(得分:1)
工厂方法模式将是理想的选择..
定义界面
interface IParser
{
public Parse(xmldoc) { ... }
public GetProperties(...) { ... }
public Validate(...) { .... }
}
现有实施
class MyParser : IParser
{
//existing implementation - using xpath & so on
}
新实施
class NewParser : IParser
{
//latest implementation with xsd & dynamic
}
工厂方法
IParser GetParser(string version)
{
switch (type)
{
case "2":
return new MyParser();
default:
throw new NewParser();
}
}
用法:GetParser(“2”)。Prase(xml);