Enum Strategy Dispatch With EnumMap
Replace switch chains with enum constants carrying behavior and an EnumMap registry so new strategies are one constant away.
Code
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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- How do you run Enum Strategy Dispatch With EnumMap?
- It runs as-is — treat the file as the whole program and execute it.
Report a problem with this exampleOpens a pre-filled issue on GitHub.