Video in progress

Strong Junior 🧭 Design patterns

How can the Strategy pattern be simplified with lambdas in Java 8+, and when do you still need a separate class?

If the Strategy interface has a single abstract method, it's a functional interface, and you can supply the strategy as a lambda or a method reference. But if the strategy has its own state, dependencies or complex logic, a separate class is easier to read and test.

📖 Answer

It used to take a class for every discount. Now:

@FunctionalInterface
interface DiscountRule {
    BigDecimal apply(BigDecimal price);
}

Map<String, DiscountRule> rules = Map.of(
    "NONE",    p -> p,
    "STUDENT", p -> p.multiply(new BigDecimal("0.90")),
    "BLACK_FRIDAY", p -> p.multiply(new BigDecimal("0.70"))
);

BigDecimal total = rules.getOrDefault(code, p -> p).apply(price);

Often you don't even need a custom interface: Function<BigDecimal, BigDecimal>, Predicate<T> or Comparator<T> is enough.

When a lambda doesn't fit:

  • the strategy needs a dependency (a repository, an external API): it's better as a class that's a Spring bean;
  • the logic grew past 5–10 lines: it gets hard to read inside a lambda, and the stack trace shows lambda$main$0;
  • the strategy has two or more methods (supports() + apply()).

In practice I use lambdas for simple rules and a separate @Component for strategies with business logic.