dimanche 16 août 2015

Creating Complex Objects from ResultSet

SQLite and Java Beginner here,

I'm currently working on a game where the player obtains random items, since I plan on including a huge amount of items, I have stored the item information in a SQLite db.

The thing is, my item objects have their own behavior objects in addition to fields like String name, int power, etc. This makes converting results to objects a more complicated endeavor. Currently I am referring to these behaviors as Strings in the db, and then instantiating the correct behavior object using a Switch statement at Item Creation. This is just a semi-fictional example to show what I mean:

Item item = new Item();

String name = resultSet.getString("Name");
String activationEffect = resultSet.getString("Activation Effect");

item.setName(name);

switch (activationEffect){
    case "Smack Fools":
        item.setActivationEffect(new SmackFools());
        break;
    case "Have a Nap":
        item.setActivationEffect(new NapTime());
        break;
    default:
        break;

Alternatively I could make item.setActivationEffect take a String and do the switch statement itself, but that doesn't really change anything. Is there a better way to accomplish this?

A second question: is there a good way to create an object representing a single row from a ResultSet / pass a ResultSet around? I would love it if I could have my database reading code and item creation code separate.

Aucun commentaire:

Enregistrer un commentaire