Strategy Pattern: Interchangeable Algorithms
Encapsulate sorting or payment algorithms behind a Strategy interface for runtime switching.
The Strategy Intent
Strategy defines a family of algorithms, encapsulates each one, and makes them interchangeable. It lets the algorithm vary independently from the context that uses it.
The Problem Without Strategy
Without Strategy, algorithm selection is buried in if-else chains. Adding a new algorithm means editing the context class — violating Open/Closed Principle.
public double sort(List<Integer> data, String method) {
if (method.equals("bubble")) { /* bubble sort */ }
else if (method.equals("merge")) { /* merge sort */ }
// adding quicksort requires editing this class
}All lessons in this course
- Observer Pattern: Event Notification
- Strategy Pattern: Interchangeable Algorithms
- Command Pattern: Encapsulating Actions
- Template Method: Defining Algorithm Skeletons