0Pricing
Java Academy · Lesson

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

  1. Observer Pattern: Event Notification
  2. Strategy Pattern: Interchangeable Algorithms
  3. Command Pattern: Encapsulating Actions
  4. Template Method: Defining Algorithm Skeletons
← Back to Java Academy