Auride
Auride

Reputation: 31

How to have constants with specific associated methods

Suppose you have some class for storing information about attacks in a game (this is not my use-case, but is practically similar and the most understandable analogy I could think of). Every attack has a name (String) and a strength (int) (There would probably be other fields, but this is just an example). And you want some way to access information about every move in the game.

To me, this would be simple enough to implement using an Attack class, then storing every attack as finalized instances of Attack in some constants class Attacks.

But suppose some moves have a strength which varies under certain circumstances. For non-trivial behaviors, I would imagine one might need a specific method, which takes parameters (the "circumstances" under which said variation occurs) causes some additional effect, such as having a higher strength in certain circumstances, or healing the user, or weakening the target, etc.

I'm looking for a solution to the problem of needing what are effectively constants (all attacks are strictly defined in terms of their behavior), but with some having "optional" methods.

I have considered using functional interfaces/objects as a way of "passing" these methods to the class which actually handles the use of these attacks, but this seems unwieldy, and may lack flexibility.

Another possible solution would be to have an abstract Attack class, containing the necessary fields (name, strength, etc.) as well as a set indicating indicating whether or not the given attack has a certain property (all of the different possible properties being stored in an enum within the Attack abstract class). Every move would then be implemented as a subclass of Attack with methods corresponding to each property present in the aforementioned set. This solution offers a lot of flexibility, but would require individual classes for every single move, which would have to collected both in storage and in memory (perhaps as a map or set).

Any feedback on these ideas, or new ideas entirely, would be appreciated.

Upvotes: 2

Views: 60

Answers (1)

gknicker
gknicker

Reputation: 5569

This is a perfect usage for an enum in Java. You have a small fixed number of attack types which need to be treated polymorphically, and need customized behavior.

Simple example:

public enum Attack {
    MELEE(2) {
        @Override
        public int getDamage(int circumstances) {
            // customized behavior
        }
    },
    RANGED(1);

    private final int baseStrength;

    private Attack(int strength) {
        this.baseStrength = strength;
    }

    public int getDamage(int circumstances) {
        // default behavior for all attacks
    }
}

Upvotes: 6

Related Questions