Behavioral Patternscritical

Strategy Pattern

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

Memory anchor

Strategy = GPS navigation modes. Same destination, but you swap the algorithm: fastest route, shortest route, avoid tolls. The car (context) doesn't care which one — it just follows the directions it's given.

Expected depth

Context class holds a reference to a Strategy interface. The strategy is injected (constructor or setter injection). Clients pick a strategy; the context executes it. Examples: sorting strategy (QuickSort, MergeSort, BucketSort — selected based on data characteristics); payment strategy (CreditCard, PayPal, Crypto — selected at checkout); compression strategy (Gzip, Brotli, LZ4 — selected based on content type). Strategy directly implements OCP: new algorithms are new classes; the context never changes.

Deep — senior internals

Strategy vs Template Method: Strategy externalizes the algorithm completely (the concrete algorithm is a separate class injected into the context); Template Method internalizes the skeleton (base class defines the steps; subclass overrides specific steps — algorithm is still part of the inheritance hierarchy). Rule of thumb: prefer Strategy when the variation is a self-contained algorithm that can be reused across multiple contexts; prefer Template Method when the variation is a small customization point within a larger fixed algorithm. In functional languages, Strategy is trivially implemented as a higher-order function — pass a function. In Java 8+, Strategy interfaces with one method are functional interfaces and can be replaced by lambdas, eliminating the need for concrete strategy classes.

🎤Interview-ready answer

Strategy is the pattern that replaces switch-case polymorphism with object polymorphism. Instead of a Sorter.sort() method with if (algorithm == 'quick') ... else if (algorithm == 'merge'), I have a SortStrategy interface with sort(int[] data) and QuickSortStrategy, MergeSortStrategy implementations. The Sorter is injected with a strategy at construction time. To add heapsort, I add HeapSortStrategy — the Sorter is untouched. In Java 8+ I can pass a method reference or lambda for simple strategies, which eliminates the ceremony of a dedicated class.

Common trap

Strategy increases the number of objects in the system. For simple cases where algorithms will never vary, the pattern is over-engineering. The signal to use Strategy is when you catch yourself writing if-else chains or switch statements based on a type/mode flag.

Related concepts