Enum Strategy Dispatch With EnumMap

Replace switch chains with enum constants carrying behavior and an EnumMap registry so new strategies are one constant away.

JavaConfig Management

Code

javasnippet
45 lines
import java.util.EnumMap;
import java.util.Map;

public class ShippingRates {

    enum Region {
        EU {
            @Override
            double baseRate(double weightKg) {
                return 5.0 + 0.8 * weightKg;
            }
        },
        NA {
            @Override
            double baseRate(double weightKg) {
                return 6.5 + 0.6 * weightKg;
            }
        },
        APAC {
            @Override
            double baseRate(double weightKg) {
                return 8.0 + 0.9 * weightKg;
            }
        };

        abstract double baseRate(double weightKg);
    }

    record Carrier(String name, Map<Region, Double> multipliers) {
        double quote(Region region, double weightKg) {
            return region.baseRate(weightKg) * multipliers.getOrDefault(region, 1.0);
        }
    }

    public static void main(String[] args) {
        Map<Region, Double> express = new EnumMap<>(Region.class);
        express.put(Region.EU, 1.5);
        express.put(Region.NA, 1.4);

        Carrier fastShip = new Carrier("fast-ship", express);
        for (Region region : Region.values()) {
            System.out.printf("%s 2kg via %s: %.2f%n", region, fastShip.name(), fastShip.quote(region, 2.0));
        }
    }
}

What the code does

Enum Strategy Dispatch With EnumMap is built around the classes ShippingRates, Region and Carrier and the function main.

Repetition is confined to for (Region region : Region.values()) — the rest of the file is straight-line.

Statements that matter

return region.baseRate(weightKg) * multipliers.getOrDefault(region, 1.0);
return 5.0 + 0.8 * weightKg;
return 6.5 + 0.6 * weightKg;

Interactive Tools for This Topic

FAQ

How do you run Enum Strategy Dispatch With EnumMap?
It runs as-is — treat the file as the whole program and execute it.