Advertisement
Intermediate Java, Design Patterns in Java

What is the Strategy pattern, and how do Java 8's functional interfaces and lambdas make implementing it significantly more concise than the traditional interface-plus-implementation-classes approach?

Short answer

Strategy defines a family of interchangeable algorithms behind a common interface, letting the algorithm used by a context object be selected/swapped at runtime -- prior to Java 8, each strategy required its own separate implementation class; with functional interfaces and…

Save Java mock interview
Advertisement
AModel answer
Strategy defines a family of interchangeable algorithms behind a common interface, letting the algorithm used by a context object be selected/swapped at runtime -- prior to Java 8, each strategy required its own separate implementation class; with functional interfaces and lambdas, a strategy can often be expressed inline as a lambda expression directly at the point of use, eliminating the boilerplate of defining a full named class for what's conceptually just a single behavior/algorithm, dramatically reducing the ceremony traditionally associated with this pattern.
public interface DiscountStrategy {
    double apply(double price);
}

public class ShoppingCart {
    private DiscountStrategy discount;
    public void setDiscount(DiscountStrategy discount) { this.discount = discount; }
    public double checkout(double total) { return discount.apply(total); }
}

ShoppingCart cart = new ShoppingCart();
cart.setDiscount(price -> price * 0.9);  // 10% off, expressed as a lambda instead of a named class
double finalPrice = cart.checkout(100.0);
Real-world example
An e-commerce checkout system swaps between different discount calculation strategies (percentage off, flat amount off, buy-one-get-one) by passing different lambda expressions implementing the same DiscountStrategy functional interface, avoiding the need to define and instantiate a separate named class for each individual discount type.
Likely follow-ups
  • What's the trade-off of using an inline lambda versus a named class implementation when the strategy logic becomes more complex?
  • How does the Strategy pattern differ conceptually from the Template Method pattern?
Related topics