FinalFind
FinalFind

Reputation: 131

Java In-Application Storage from Xml Data

Hi I am developing a game in Java for learning purposes and have a question regarding in-app handling of data

Say I have a bunch of xml files storing a variety of statistics for, weapons armours etc and I parse these files into my application as lists;

Note, this data will never change and is effectively "final", it is constant data that will be used by the game.

Now my question is, would you store this data (for use while the game is running) in a class (in my example here a singleton) within your application that you can access easily? So for example something like this (where the list has been read elsewhere by the XML parser)

public class WeaponData {

   private List<Weapon> weaponData;

   public static final WeaponData instance = new WeaponData(parseXml("weapons"));


   private WeaponData(List<Weapon> data) {
       weaponData = data;
   }

   public static WeaponData getInstance() {
       return instance;
   }

   public List<Weapon> getWeaponData() {
       return weaponData;
   }
}

And allows me to use the data with

WeaponData.getInstance().getWeaponData();

If so, is this the way to go about it, or is there a better way?

Or, the only alternative I can think of, is to keep reading the XML whenever its needed (which seems unwise, paticularly given, this data retrieval may (for a commercial application atleast) be a network operation, even if in my case it is just a hdd read). Plus if anything else it would be repeated code.

Thanks for your time!

Upvotes: 0

Views: 83

Answers (2)

Keith
Keith

Reputation: 3151

I'm thinking that your approach will work, especially as you have mentioned that the data won't become large enough that it imposes on memory. Another concern would be the frequency in which you must read the data. There's a tradeoff between those two considerations, but it sounds like the small XML size warrants unmarshalling the XML into objects immediately.

Just for completeness, you should be using JAX-B to generate Java classes from your XML schema, rather than rolling your own parser.

If you fear that the XML's data may change, you might consider using the WatchService API to detect changes and re-parse the XML file.

Upvotes: 0

Bill K
Bill K

Reputation: 62769

You should probably read it in once and save it, but don't store it as a singleton. Read the WeaponData during initialization and store an instance of it. If you don't like that you are welcome to use the pattern you suggested, it just might be awkward later.

If you ever get to where WeaponData might be updated while the app is running, you may want to re-read it, but not ever time.

Upvotes: 1

Related Questions