design patterns · medium
GoF Strategy — Pluggable Interchangeable Algorithms
The Strategy pattern encapsulates a family of algorithms in interchangeable classes. A SortStrategy interface defines sort(); concrete classes (BubbleSortStrategy, QuickSortStrategy, RadixSortStrategy) each implement the algorithm independently. The Context (Sorter) holds a SortStrategy* pointer, delegates sort() to strategy_->sort(v), and exposes setStrategy() so the client can swap the algorithm at runtime. Adding a new algorithm = adding a new class only (OCP). Each strategy is independently testable. Strategy vs State: both use the same polymorphism; Strategy is about pluggable algorithms set from outside; State is about an object transitioning itself through different behaviours based on internal conditions.
Strategy: define a family of algorithms as interchangeable classes sharing one interface; Context holds Strategy* and delegates; client injects the desired strategy — swappable at runtime, satisfies OCP.
The code
// Strategy interfaceclass SortStrategy {public: virtual void sort(std::vector<int>& v) = 0; virtual ~SortStrategy() = default;};
// Concrete strategies — interchangeable algorithmsclass BubbleSortStrategy : public SortStrategy { void sort(std::vector<int>& v) override { /* O(n²) */ }};class QuickSortStrategy : public SortStrategy { void sort(std::vector<int>& v) override { /* O(n log n) */ }};class RadixSortStrategy : public SortStrategy { void sort(std::vector<int>& v) override { /* O(nk) integers only */ }};
// Context: holds a strategy, delegates work to itclass Sorter { SortStrategy* strategy_;
public: Sorter(SortStrategy* s) : strategy_(s) {} void setStrategy(SortStrategy* s) { strategy_ = s; } // swap at runtime void sort(std::vector<int>& v) { strategy_->sort(v); } // delegate};
// Client: injects strategy; context code unchangedstd::vector<int> data = {5, 2, 8, 1, 9};Sorter sorter(new QuickSortStrategy());sorter.sort(data); // uses QuickSort
sorter.setStrategy(new RadixSortStrategy()); // swap at runtimesorter.sort(data); // now uses RadixSort — Sorter unchangedWhat this lesson walks through
- 01The problem: switch-on-algorithm violates OCP
- 02Strategy interface — context only knows this
- 03QuickSortStrategy selected — context unchanged
- 04setStrategy() — swap algorithm at runtime
- 05Adding BubbleSort — zero changes to Sorter or other strategies
- 06Strategy vs State pattern — a common interview question
Without Strategy, the Context (Sorter) has a switch deciding which algorithm to run. Adding a new algorithm means editing the Sorter class — violating OCP. The Sorter also becomes long and hard to test each algorithm in isolation.
See it animated — step by step, at your own pace
Unlock the full interactive walkthrough of GoF Strategy — Pluggable Interchangeable Algorithms and 100+ animated C++ interview lessons.