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.
The file might look like
<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>
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.
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).
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?
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.