What is the Strategy pattern?
Why Interviewers Ask This
This question targets practical, hands-on experience with OOP Concepts. Interviewers want to see if you've worked with these concepts in real projects, not just read about them. Strong answers include concrete examples.
Answer
The Strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. It lets the algorithm vary independently from clients that use it. Replaces complex if/else or switch statements for algorithm selection. Example — sorting strategy: interface SortStrategy<T extends Comparable<T>> { void sort(List<T> data); } class BubbleSortStrategy<T extends Comparable<T>> implements SortStrategy<T> { @Override public void sort(List<T> data) { // Bubble sort implementation } } class QuickSortStrategy<T extends Comparable<T>> implements SortStrategy<T> { @Override public void sort(List<T> data) { // Quick sort implementation } } class DataSorter<T extends Comparable<T>> { private SortStrategy<T> strategy; public DataSorter(SortStrategy<T> strategy) { this.strategy = strategy; } public void setStrategy(SortStrategy<T> strategy) { this.strategy = strategy; // Can switch at runtime! } public void sort(List<T> data) { strategy.sort(data); } } // Usage: DataSorter<Integer> sorter = new DataSorter<>(new QuickSortStrategy<>()); sorter.sort(largeData); // Use quick sort for large data sorter.setStrategy(new BubbleSortStrategy<>()); sorter.sort(smallData); // Switch to bubble sort. Another example — payment strategy: interface PaymentStrategy { void pay(double amount); } class CreditCardPayment implements PaymentStrategy { void pay(double a) { /* charge card */ } } class PayPalPayment implements PaymentStrategy { void pay(double a) { /* PayPal API */ } } class Checkout { private PaymentStrategy paymentMethod; void processPayment(double total) { paymentMethod.pay(total); } }. Benefits: Open/Closed Principle, eliminate conditionals, swap algorithms at runtime, test strategies independently.
Pro Tip
Back up your answer with a specific project or situation. Saying 'In my last OOP Concepts project, I used this when...' immediately makes your answer more credible and memorable.