In this article, we will learn how to use and implement the Strategy Pattern in C++ with an example.
Strategy pattern defines a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from the clients that use it.
C++ Strategy Pattern Example
The below diagram shows the generic structure of the Strategy Pattern:
Let's refer to the above structure to create an example to demonstrates the usage of the Strategy Pattern.
#include <iostream> /* * Strategy * declares an interface common to all supported algorithms */ class Strategy { public: virtual ~Strategy() { /* ... */ } virtual void algorithmInterface() = 0; }; /* * Concrete Strategies * implement the algorithm using the Strategy interface */ class ConcreteStrategyA : public Strategy { public: ~ConcreteStrategyA() { /* ... */ } void algorithmInterface() { std::cout << "Concrete Strategy A" << std::endl; } }; class ConcreteStrategyB : public Strategy { public: ~ConcreteStrategyB() { /* ... */ } void algorithmInterface() { std::cout << "Concrete Strategy B" << std::endl; } }; class ConcreteStrategyC : public Strategy { public: ~ConcreteStrategyC() { /* ... */ } void algorithmInterface() { std::cout << "Concrete Strategy C" << std::endl; } }; /* * Context * maintains a reference to a Strategy object */ class Context { public: Context( Strategy* const s ) : strategy( s ) {} ~Context() { delete strategy; } void contextInterface() { strategy->algorithmInterface(); } private: Strategy *strategy; }; int main() { Context context( new ConcreteStrategyA() ); context.contextInterface(); Context context1( new ConcreteStrategyB() ); context1.contextInterface(); Context context2( new ConcreteStrategyC() ); context2.contextInterface(); return 0; }
Output
Concrete Strategy A
Concrete Strategy B
Concrete Strategy C
When to use?
- many related classes differ only in their behavior
- you need different variants of an algorithm
- an algorithm uses data that clients shouldn't know about
Related C++ Design Patterns
- C++ Factory Method Pattern Example
- C++ Builder Pattern Example
- C++ Abstract Factory Pattern Example
- C++ Bridge Pattern Example
- C++ Chain of Responsibility Pattern Example
- C++ Composite Pattern Example
- C++ Decorator Pattern Example
- C++ Facade Pattern Example
- C++ Mediator Pattern Example
- C++ Memento Pattern Example
- C++ Observer Pattern Example
- C++ Proxy Pattern Example
- C++ Strategy Pattern Example
- C++ State Pattern Example
- C++ Visitor Pattern Example