diff --git a/strategy/README.txt b/strategy/README.txt new file mode 100644 index 0000000..151073e --- /dev/null +++ b/strategy/README.txt @@ -0,0 +1,11 @@ +## Strategy + +Strategy defines a family of algorithms, encapsulates each one, and makes them +interchangeable. It lets the algorithm vary independently fromclients that use it. +The pattern has behavioral purpose and applies to the objects. + +### 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 \ No newline at end of file diff --git a/strategy/Strategy.cpp b/strategy/Strategy.cpp new file mode 100644 index 0000000..fd502ab --- /dev/null +++ b/strategy/Strategy.cpp @@ -0,0 +1,92 @@ +/* + * C++ Design Patterns: Strategy + * Author: Jakub Vojvoda [github.com/JakubVojvoda] + * 2016 + * + * Source code is licensed under MIT License + * (for more details see LICENSE) + * + */ + +#include + +/* + * 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 *s) + : strategy(s) {} + + ~Context() { + delete strategy; + } + + void contextInterface() { + strategy->algorithmInterface(); + } + // ... + +private: + Strategy *strategy; + // ... +}; + + +int main() +{ + ConcreteStrategyA strategy; + // ConcreteStrategyB strategy; + // ConcreteStrategyC strategy; + + Context context(&strategy); + context.contextInterface(); + + return 0; +}