×

java · level 3 · unit 7 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A is one swappable way of doing a job.

A is a well-known shape for a common problem. Naming it saves explaining it: say "strategy" and another developer knows the plan. You have met the idea already, because a Comparator is a strategy for sorting.

The strategy pattern puts each way of doing a job behind one interface. A shop might charge delivery at a flat rate, by weight, or not at all. Each rule is a lambda, and the checkout asks whichever rule it was given.

Keep strategies in a Map by name, and a new rule is one new line, with no edits to the checkout. Look them up with getOrDefault, so an unknown name gets a safe default instead of null.

import java.util.Map;
public class Main {
    @FunctionalInterface
    interface Delivery {
        int costPence(int grams);
    }
    static String quote(Map<String, Delivery> rules, String method, int grams) {
        Delivery rule = rules.getOrDefault(method, rules.get("standard"));
        return method + ": " + rule.costPence(grams) + "p";
    }
    public static void main(String[] args) {
        Map<String, Delivery> rules = Map.of(
            "standard", grams -> 399,
            "express", grams -> 500 + grams / 100 * 15,
            "collect", grams -> 0);
        System.out.println(quote(rules, "express", 2000));
        System.out.println(quote(rules, "collect", 9500));
        System.out.println(quote(rules, "pigeon", 300));
    }
}

quote never changes when a new rule arrives. That is the whole point of the pattern.