Design patterns and domain modeling
Strategy
Encapsulate a selectable policy. Executed Java 21 fixture.
Formal Syntax & Structure
java syntaxjava
Delivery.fee(n)Working Example
Example Snippetjava
public class Main { interface Delivery { int fee(int quantity); } static int before(String kind, int n) { return switch (kind) { case "pickup" -> 0; case "courier" -> n == 0 ? 0 : 500; default -> throw new IllegalArgumentException("kind"); }; } static Delivery choose(String kind) { return switch (kind) { case "pickup" -> n -> 0; case "courier" -> n -> n == 0 ? 0 : 500; default -> throw new IllegalArgumentException("kind"); }; } public static void main(String[] args) { for (String kind : java.util.List.of("pickup", "courier")) { for (int n : new int[]{0, 2}) { int old = before(kind, n); int result = choose(kind).fee(n); if (old != result) throw new AssertionError(); System.out.println(kind + ": " + result); } } }}