Strategy Pattern: Interchangeable Algorithms
Encapsulate sorting or payment algorithms behind a Strategy interface for runtime switching.
Strategy Pattern: Interchangeable Algorithms is a free Java Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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
}Strategy Interface
Define a @FunctionalInterface or regular interface representing the algorithm contract. Each implementation encapsulates a different algorithm.
public interface SortStrategy {
void sort(List<Integer> data);
}
public class BubbleSortStrategy implements SortStrategy {
public void sort(List<Integer> data) { /* bubble sort logic */ }
}
public class QuickSortStrategy implements SortStrategy {
public void sort(List<Integer> data) { Collections.sort(data); }
}Context Class
The context holds a reference to a strategy and delegates algorithm execution to it. The strategy can be swapped at runtime.
public class Sorter {
private SortStrategy strategy;
public Sorter(SortStrategy strategy) { this.strategy = strategy; }
public void setStrategy(SortStrategy s) { this.strategy = s; }
public void sort(List<Integer> data) { strategy.sort(data); }
}Switching Strategies at Runtime
Change the strategy on the fly without modifying the context. This makes behavior configurable from outside the class.
Sorter sorter = new Sorter(new BubbleSortStrategy());
sorter.sort(data); // uses bubble sort
sorter.setStrategy(new QuickSortStrategy());
sorter.sort(data); // now uses quick sortLambda Strategies
When the strategy interface is a @FunctionalInterface, use lambdas directly — no need for explicit classes for simple strategies.
Sorter sorter = new Sorter(data -> Collections.sort(data)); // lambda strategy
// or method reference:
Sorter sorter2 = new Sorter(Collections::sort);Strategy for Payment Processing
Classic real-world use: a payment context accepts different payment strategies (credit card, PayPal, crypto) without knowing the details of each.
public interface PaymentStrategy {
void pay(double amount);
}
new PaymentProcessor(new CreditCardStrategy("4111...")).pay(99.99);
new PaymentProcessor(new PayPalStrategy("user@email.com")).pay(99.99);Strategy for Compression
A file processor can use a CompressionStrategy. Plug in GZIP, ZIP, or LZ4 without changing the file-processing pipeline.
public interface CompressionStrategy {
byte[] compress(byte[] data) throws IOException;
}
public class GzipStrategy implements CompressionStrategy {
public byte[] compress(byte[] data) throws IOException { /* gzip */ return new byte[0]; }
}Combining Strategy with Factory
Use a factory to select the strategy based on configuration, keeping the selection logic separate from both the context and the strategies themselves.
SortStrategy strategy = switch (config.getSortMethod()) {
case "bubble" -> new BubbleSortStrategy();
case "merge" -> new MergeSortStrategy();
default -> Collections::sort;
};
new Sorter(strategy).sort(data);Strategy vs Template Method
Template Method uses inheritance: the skeleton is in the base class; subclasses override steps. Strategy uses composition: the algorithm is entirely external. Prefer Strategy for greater flexibility.
Strategy in the JDK
Comparator is the canonical JDK Strategy. Pass different comparators to Collections.sort to change the ordering algorithm without touching the collection code.
List<String> names = List.of("Bob", "Alice", "Charlie");
names.stream().sorted(Comparator.comparingInt(String::length)).forEach(System.out::println);Testing Strategies
Strategies are easy to test in isolation — just call strategy.sort(data) in a unit test. Inject mock strategies into the context to test the context's orchestration logic.
Quick Check
What is the key structural difference between Strategy and Template Method?
Recap
Strategy encapsulates interchangeable algorithms behind a common interface. Use lambdas for simple strategies, classes for complex ones. Combine with factories for config-driven selection.
Frequently asked questions
Is the “Strategy Pattern: Interchangeable Algorithms” lesson free?
Yes — the full text of “Strategy Pattern: Interchangeable Algorithms” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.
What will I learn in “Strategy Pattern: Interchangeable Algorithms”?
Encapsulate sorting or payment algorithms behind a Strategy interface for runtime switching. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Java Academy?
No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Strategy Pattern: Interchangeable Algorithms” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Java Academy lesson?
Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Observer Pattern: Event Notification
- Strategy Pattern: Interchangeable Algorithms
- Command Pattern: Encapsulating Actions
- Template Method: Defining Algorithm Skeletons