🧩 OOP Concepts Intermediate

What is the Strategy pattern?

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.