Strategy Pattern — Replacing If-Else Chains
Fast recall
Quick revision
Core answer
Open/Closed Principle understanding and practical refactoring skill
Using a single strategy class with an internal if-else — that just moves the problem without solving it
Show map-based strategy selection, Spring @Component with qualifier injection as a strategy registry, and functional interface strategies with lambdas
Interview-ready guide
Interview answer
The Strategy pattern replaces open-ended if-else chains by encapsulating each algorithm in its own class behind a shared interface. The key insight is that branching on a 'type' field to select different behavior is a sign the varying logic should be pulled out into separate strategy objects.
The implementation starts with a Strategy interface declaring the common contract — same inputs, same output, different computation. Each concrete strategy implements the interface. The context class, instead of containing a switch, holds a map from type to strategy and delegates directly.
In Spring, the most powerful approach is annotating each strategy with @Component and injecting all implementations via List. You build a lookup map in the constructor, and dispatch is a single map.get(type).apply(...) call — no conditionals. Adding a new variant means adding a new @Component class. The dispatch logic and existing strategies are untouched.
The mistake interviewers watch for is creating strategy classes but keeping a switch to choose among them — that just relocates the conditional without solving the problem.
With Java 8+ functional interfaces, lightweight strategies can be expressed as lambdas in a Map. This is concise for simple algorithms but loses Spring lifecycle management and independent testability. My rule: use lambda strategies for 1-3 line algorithms in config, full classes for anything with dependencies or complex logic. And don't apply Strategy at all if you have two branches that won't grow — it's overkill.
Strategy Pattern — Replacing If-Else Chains
Direct Answer
The Strategy pattern encapsulates each algorithm behind a common interface. Instead of a growing if-else or switch block that selects behavior, you inject the appropriate strategy object. In Java this is often combined with a Map<String, Strategy> for O(1) dispatch, eliminating conditionals entirely.
Common Mistakes & Pitfalls
Using a single strategy class with an internal if-else — that just moves the problem without solving it
Check your understanding
Answer these without looking back at the article.
- How do you handle strategy selection when the choice depends on multiple conditions?
- What is the difference between Strategy and State patterns?
- How would you combine Strategy with Factory for strategy creation?
Related interview prep categories
2Want a guided curriculum order?
These modules are also sequenced in our flagship backend interview track — open it when you prefer an ordered path instead of browsing by topic.