BehavioralC++verifiedVerified

Strategy Pattern in C++

Defines a family of algorithms, encapsulates each one, and makes them interchangeable so the algorithm can vary independently from the clients that use it.

How to Implement the Strategy Pattern in C++

1Step 1: Define the strategy as a callable type

using SortStrategy = std::function<void(std::vector<int>&)>;

2Step 2: Concrete strategies

SortStrategy bubbleSort = [](std::vector<int>& v) {
    for (size_t i = 0; i < v.size(); ++i)
        for (size_t j = 0; j + 1 < v.size() - i; ++j)
            if (v[j] > v[j + 1]) std::swap(v[j], v[j + 1]);
};

SortStrategy stdSort = [](std::vector<int>& v) {
    std::sort(v.begin(), v.end());
};

3Step 3: Context that uses a strategy

class Sorter {
    SortStrategy strategy_;
public:
    explicit Sorter(SortStrategy strategy) : strategy_(std::move(strategy)) {}
    void setStrategy(SortStrategy strategy) { strategy_ = std::move(strategy); }

    void sort(std::vector<int>& data) { strategy_(data); }
};

4Step 4: Swap strategies at runtime

int main() {
    std::vector<int> data = {5, 2, 8, 1, 9};

    Sorter sorter(bubbleSort);
    sorter.sort(data);
    for (int x : data) std::cout << x << " ";
    std::cout << "\n";

    data = {5, 2, 8, 1, 9};
    sorter.setStrategy(stdSort);
    sorter.sort(data);
    for (int x : data) std::cout << x << " ";
    std::cout << "\n";
}

Strategy Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Strategy Pattern in the Real World

Consider a GPS app offering route options: fastest, shortest, or avoid tolls. The destination is the same, but the navigation algorithm changes based on your preference. The app (context) simply hands the journey off to whichever routing strategy you selected; you can switch strategies mid-trip without the app needing to change its structure.