Skip to content
Sharp

Design patterns · interview question

Explain the Strategy pattern with a concrete Java example. When would you use it?

Interview answerMedium

0 words · aim for 40+

Answer and explanation

Correct answer

Strategy defines a family of interchangeable algorithms behind a common interface and lets the client pick one at runtime, instead of hard-coding it with if/else or switch.

Example: interface ShippingCostStrategy { BigDecimal cost(Order o); } with implementations FlatRate, ByWeight and FreeOverThreshold. Checkout takes a strategy in its constructor and calls strategy.cost(order). Since the interface has one method, a lambda works too: new Checkout(o -> BigDecimal.ZERO). Comparator passed to List.sort is a built-in Strategy.

Use it when behavior varies by configuration, customer or context, when you want to add algorithms without modifying the client (open/closed principle), and to make each algorithm testable on its own.

Key points:
- Interchangeable algorithms behind a common interface
- The client receives and uses the strategy (composition), chosen at runtime
- Gives a concrete example (e.g. pricing, sorting with Comparator)
- Replaces conditionals; supports the open/closed principle
- Lambdas or functional interfaces can implement strategies

Why

Pointing at Comparator as a JDK Strategy is an easy win.

References

  • Gamma, Helm, Johnson & Vlissides, Design Patterns: Elements of Reusable Object-Oriented Software (1994)
  • Joshua Bloch, Effective Java, 3rd ed. (2018)

Test yourself on Design patterns

A free test with instant, explained results. No account needed.

Start free test
All Design patterns questions →