0
\$\begingroup\$

I have recently been programming an Entity Component System in Java for a small game that I am working on. From what I have tested, it works rather well however I question the component part. I currently have an Entity class that stores subclasses of Component in a HashMap which can be accessed by a String:

private Map<String, Component> components = new HashMap<String, Component>();

The problem is that my root Component class looks like this:

public class Component {

}

I feel as if I've headed in the wrong direction so my question is do I need a Component super class? If so, is there anything that needs to be put in it? If not, should I have a HashMap of Objects instead? Are there advantages to either methods?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Your component base-class seems to be empty now, but it's just a question of time until you will find functionality to add to it. A good candidate might be an update() function which you likely want to have on almost any kind of component.

In the meantime you might want to change it to an interface. That would make it a pure marker interface: An interface which defines no functionality, but marks classes which fulfill some specific purpose or implement some contract, like in your case, being a component.

And by the way: If you want to allow one component per component-type on each entity, you might want to define your hash map as a Map<Class, Component>. You addComponent method would then do this:

public void addComponent(Component newComponent) {
     components.put(newComponent.getClass(), newComponent);
}

GetComponent looks like this:

public Component getComponent(Class type) {
    return components.get(type);
}

and would be called like this:

getComponent(PlayerControllerComponent.class);

This should be a bit faster and gives you the advantage of type-safety (you can no longer misspell your component identification strings).

\$\endgroup\$
1
  • \$\begingroup\$ Wow, thanks for the fast reply and that marker interface concept is pretty much exactly what I need for that class. Also, having a Map that can be accessed with classes that extend Component seems to be a much more secure way of storing components. :) \$\endgroup\$ Commented Mar 12, 2017 at 23:22

You must log in to answer this question.