Design patterns · interview question
Explain the Strategy pattern with a concrete Java example. When would you use it?
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.
More Design patterns questions
- Your checkout flow wants one clean charge(order) call, but each payment provider ships a different SDK. Which design…
- Which principle is most closely aligned with the Factory Pattern?
- Which scenario is least suited for the Decorator pattern?
- Why is it important for a decorator to share the same interface as the object it decorates?
- In an e-commerce application, you want to delay loading product images until they are actually needed. Which design…
- You are designing a system with multiple types of notifications (email, SMS, push). How can the Factory Pattern help…