All 15 Enums questions
More in Enums
Advertisement
Back to results for “Enums”
Java › Enums

How would you implement the Strategy pattern using an enum with constant-specific method bodies, and how does this compare to a traditional interface-based Strategy implementation?

Advanced

Answer

An enum can have each individual constant override an abstract method with its own unique implementation (a "constant-specific class body"), letting the enum itself directly encapsulate a fixed, closed set of interchangeable algorithms/strategies without needing separate implementation classes -- this is a particularly clean fit specifically when the set of strategies is genuinely fixed and known in advance (unlike a general Strategy pattern via an interface, which supports an open-ended, extensible set of implementations), trading that extensibility for enum's built-in singleton-per-constant simplicity and exhaustiveness-checkable switch support.
public enum Operation {
    ADD { public double apply(double a, double b) { return a + b; } },
    SUBTRACT { public double apply(double a, double b) { return a - b; } },
    MULTIPLY { public double apply(double a, double b) { return a * b; } };

    public abstract double apply(double a, double b);  // each constant provides its own implementation
}

double result = Operation.ADD.apply(3, 4);  // 7.0, dispatches directly to ADD's own implementation
Real-world example A simple calculator's arithmetic operations are modeled as an Operation enum with constant-specific apply() implementations, avoiding both a large if/else or switch chain AND the need for four separate small implementation classes that a traditional interface-based Strategy pattern would require for this same fixed, closed set of operations.

Common follow-ups: When would a traditional interface-based Strategy implementation still be preferable to this enum-based approach?;What's the memory/performance characteristic of constant-specific method bodies compared to a switch-based dispatch?