用于从XML文件实例化对象的设计范例 [英] Design Paradigm for instantiating object from XML file

查看:175
本文介绍了用于从XML文件实例化对象的设计范例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于一个单独的任务,我正在编写一个需要保存并将对象层次结构加载到XML文件的java程序。例如,程序创建一个Zoo类,其中包含动物子类列表,将其保存为XML,并在下次用户启动程序时再次加载。

For a uni assignment I'm writing a java program which needs to save and load an object hierarchy to XML files. For example, the program creates a Zoo class with a list of subclasses of Animals, saves this to XML, and is loaded again the next time the user starts the program.

该文件可能看起来像

<Zoo>
    <Animals>
        <Lion>
            <name>Leo</name>
            <age>5</age>
            <roar>fearsome</roar>
        </Lion>
        <Elephant>
            <name>Dumbo</name>
            <age>10</age>
            <ears>let him fly</ears>
        </Elephant>
    </Animals>
</Zoo>

我需要支持(〜5)动物的子类数量有限。动物的每个子类具有个体属性(如耳朵和吼声)。我对于创建和创建对象的最佳设计模式感到困惑。

There is a low, finite number of subclasses of Animal I need to support (~5). Each subclass of animal has individual attributes (like Ears and Roar). I'm confused as to what the best design pattern for object creation and file creation is.

目前,我有一个类, XMLCreator ,方法如 void createZooElement(Zoo) void createLionElement(Lion)等等,和一个具有 private Zoo createZoo(File) private Lion createLionObject(Element)的XMLReader类。

Currently, I have a class, XMLCreator, with methods such as void createZooElement(Zoo), void createLionElement(Lion) etc etc, and an XMLReader class with private Zoo createZoo(File), private Lion createLionObject(Element).

这是一个很好的方法,如果这是你以后会被其他人维护的代码?或者每个对象应该有一个构造函数方法,它将一个File / Element作为参数,另一个方法返回一个File / XMLElement?封装/可维护性最强的方式是什么?

Is this a good way to go if this were code you expect to be maintained by others in the future? Or should each object have a constructor method which takes a File/Element as a parameter and another method which returns a File/XMLElement? Which is the way with the most encapsulation/maintainability?

推荐答案

我只会使用 JAXB ,它允许编组一个对象(注释类)到XML,并将XML解组到一个树的对象。还有其他的对象到XML API,但JAXB自带Java SE,并且运行良好。

I would just use JAXB, which allows marshalling a tree of objects (of annotated classes) to XML, and unmarshalling XML to a tree of objects. There are other Object to XML APIs, but JAXB comes with Java SE and works well.

这篇关于用于从XML文件实例化对象的设计范例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆