C++ Strategy Pattern Example

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