Strategy Pattern in C++: What It Is and How It Works
Strategy Pattern in C++ is a design pattern that lets you define a family of algorithms, put each one in a separate class, and make them interchangeable. It allows a program to choose the algorithm at runtime without changing the code that uses it.How It Works
Imagine you have a remote control that can change the way a robot moves: it can walk, run, or jump. Instead of building a new robot for each movement, you just change the remote's setting. The Strategy Pattern works like this remote control. It separates the behavior (algorithm) from the main program, so you can swap behaviors easily.
In C++, this means you create a common interface for all strategies (algorithms). Then, each strategy is a class that implements this interface. The main program holds a pointer or reference to the interface and calls the algorithm through it. You can change the strategy object anytime to change the behavior without touching the main code.
Example
This example shows a simple calculator that can perform different operations like addition and multiplication using the Strategy Pattern.
#include <iostream> #include <memory> // Strategy interface class Operation { public: virtual int execute(int a, int b) const = 0; virtual ~Operation() = default; }; // Concrete strategy for addition class AddOperation : public Operation { public: int execute(int a, int b) const override { return a + b; } }; // Concrete strategy for multiplication class MultiplyOperation : public Operation { public: int execute(int a, int b) const override { return a * b; } }; // Context class that uses a strategy class Calculator { private: std::unique_ptr<Operation> strategy; public: void setStrategy(std::unique_ptr<Operation> op) { strategy = std::move(op); } int calculate(int a, int b) const { if (strategy) { return strategy->execute(a, b); } return 0; } }; int main() { Calculator calc; calc.setStrategy(std::make_unique<AddOperation>()); std::cout << "Add: " << calc.calculate(5, 3) << "\n"; calc.setStrategy(std::make_unique<MultiplyOperation>()); std::cout << "Multiply: " << calc.calculate(5, 3) << "\n"; return 0; }
When to Use
Use the Strategy Pattern when you have multiple ways to do something, and you want to switch between these ways easily without changing the main program. It is helpful when you want to add new algorithms without touching existing code, making your program flexible and easier to maintain.
Real-world examples include sorting algorithms in a library where users can pick the best one, payment methods in an online store where you can add new payment options, or different ways to compress files in a tool.
Key Points
- The Strategy Pattern separates algorithms from the code that uses them.
- It uses a common interface for all strategies.
- Strategies can be changed at runtime.
- It helps keep code flexible and easy to extend.