Jake1996 Jake1996 - 1 year ago 61
Java Question

How do i create different instances of a class using Enumerations as an identifier?

Hi im having problems with my game project because i require "extended" classes which have slightly different functions and creating an instance of Entity with just different names wont work properly since some classes have been extended.

Basically i have an entity class with different entities extending and implementing different classes, but i want to learn the best way of creating instances of each class just by using an enumeration. For example: new Entity(Enum.ZOMBIE) or new Entity(Enum.SPIDER)

Im doing it this way because my spawner's are designed to spawn in different types of creatures based on user input, and if i make an else if or switch method it will become very very long.

How would you solve this issue? Maybe inside my main class have a switch/case and return an instance of the modified class?

Sorry if this doesn't make sense, i'm having trouble explaining how its supposed to work.


Answer Source

You need a lookup table to store the name of the class with the way to create an instance of that class.

Assuming you have an Entity class and several classes that extends it: Zombie, Spider, Hero. You define an interface that creates an entity:

interface EntityFactory {
    Entity create();

And a "table" to store the mapping from a name to instances of this interface:

Map<String, EntityFactory> factories = new HashMap<>();

Then you register your sub class factories:

factories.put("Zombie", Zombie::new);
factories.put("Spider", Spider::new);
factories.put("Hero", Hero::new);

And a util method that does the lookup and calling the appropriate factory:

Entity create(String name) {
    EntityFactory factory = factories.get(name);
    if (factory == null) {
        throw new NoSuchElementException();
    return factory.create();

Now you can create entities from user input, as long as you register all entity classes:

Entity spider0 = create("Spider");
Entity hero0 = create("Hero");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download