1

I'm writing a game API, and I'd like there to be an enum of controls. I want to define basic controls (JUMP, MOVE_LEFT), but the end developer should be able to add other controls (DANCE, SHOOT).

So how would I allow the end programmer to add to my list without having to touch my original enum file?

Joel Christophel
  • 2,604
  • 4
  • 30
  • 49

2 Answers2

1

As the linked answer points out you can't extend an enum directly.

Your question doesn't provide that much information to work with but here is how I'd approach the problem. Hopefully it will be of some benefit.

First I would define an abstraction to encapsulate the actual logic that is carried out for each 'control'.

interface Behaviour {
    void invoke();
}

Objects that implement this interface would override the invoke() method to provide the actual control logic such as moving your game object left or right.

Your API could have a method like the one below which carries out whatever action is appropriate to the control the method is invoked on.

public void moveObjectAccordingTo(Behaviour behaviour) {
    behaviour.invoke();
    // Whatever else you want to do...
}

The enum that contains your default controls can then implement this interface, something like this:

public enum Controls implements Behaviour {
    JUMP("Player jumped..."),
    MOVE_LEFT("Player moved left..."),
    MOVE_RIGHT("Player moved right...");

    private final String message;

    Controls(String message) {
        this.message = message;
    }

    @Override    
    public void invoke() {
        System.out.println(message);
    }
}

This allows you to use the previous method like this:

public void moveObjectAccordingTo(Controls.JUMP);

Now, you want developers to be able to add their own additional controls to the system without affecting the enum. All you have to do is implement the Behaviour interface and override the invoke method. Like this:

public class DanceControl implements Behaviour {

    @Override
    public void invoke() {
        System.out.println("Player is dancing...");
    }
}

The new behaviour can then be consumed without changing your original enum or without having to alter the API.

public void moveObjectAccordingTo(new DanceControl());
Benjamin Gale
  • 12,977
  • 6
  • 62
  • 100
1

Your approach is not good because in Java you can't extend enum. Enum type in Java is final by design.

More about enum you can find in official documentation.

So, by design, enum type should have only the elements declared in the enum.

Instead of this you should to consider to use interfaces in your approach.

Bosko Mijin
  • 3,287
  • 3
  • 32
  • 45