Home > Enterprise >  Design question about instantiating objects in Java
Design question about instantiating objects in Java

Time:09-14

my responses may be slow, but I had a design question I'm hoping to get some advice on:

I'm trying to make a fight simulator for a phone game I play. I have a class representing each hero, which implements their particular abilities' logic. They inherit an abstract Hero class, which itself inherits an abstract Unit class.

The Unit class holds the stats and effects (buff and debuffs), Hero has abstract methods for ability logic, and the individual heroes implement said methods.

Now the part I can't figure out, is I have a very basic GUI, where you can select up to four heroes from drop-down lists. And I need a way to then create the specific hero class objects needed for the rest of my program based on what they select.

But I obviously can't use the dropdown value as a class type, so am I forced to just make some massive switch case for them all or something? Or is there a more elegant method people use that I'm just not thinking of?

There would eventually be over 100 unique heroes (and therefore classes), and I'm just struggling with how to efficiently create objects only for the ones selected in my dropdown menus. Once they're made, I plan to add them to a small array of type Hero (their super class) and then just reference by index going forward.

It's just how to go about filling the array up that's causing me to get stuck.

Sorry for rambling, but hoping that explains things well enough. And just to be clear, I'm writing this all in Java and using JavaFX for the GUI.

CodePudding user response:

And I need a way to then create the specific hero class objects needed for the rest of my program based on what they select

I don't know if you know SQL, The way that you'd do this using a SQL database is to have 1 table for heroes, 1 table for all hero objects, and then a table that references both a hero and a hero object. Then you could query all the hero objects via

select Object from HeroObjectTbl where hero = ??

If you don't know SQL, do you know how to use any other database technology? IMO you really need a DB for this

CodePudding user response:

You can create an array of functions (sort of) in which each function creates a different hero.

public interface HeroCreator() {
  public Hero create();
}

Then, you instantiate the array in the beginning of your game:

  (...)
  public HeroCreator[] creators = {
    new HeroCreator() { 
      @override public void create() {
        return new Hero1();
      }
    },
    new HeroCreator() { 
      @override public void create() {
        return new Hero2();
      }
    },
    (...)
  };
  (...)

Finally, you just get a position i from you combobox and call the creator at that position:

i = (...)

Hero hero = creators[i].create();

Disclaimer: I did not check the code for typos and other errors, but the logic is this.

  •  Tags:  
  • java
  • Related