Search code examples
c++inheritancedesign-patternsstrategy-patternobject-oriented-analysis

Differences between Strategy Pattern and Inheritance


There is a same concept for Strategy Pattern and Inheritance, so I can implement Strategy Pattern with Inheritance that sounds it is simpler and cleaner than Strategy Pattern.

Startegy Pattern:

class IBase
{
public:
    virtual void processAction(void *data) = 0; // pure virtual
}

class Worker: public IBase
{
public:
    virtual void processAction(void *data)
    {
        // define logic
    }
}

Inheritance:

class Base
{
public:
    virtual void processAction(void *data) {}
}

class Worker: public Base
{
public:
    virtual void processAction(void *data) override
    {
        // define logic
    }
}

My question is what is the difference between them? or when should I use Strategy Pattern or Inheritance?

Link: Strategy Pattern


Solution

  • Imagine you design a Cache. The cache can have options regarding

    • eviction policy (LIFO, FIFO, LRU)
    • expiration policy (after read, after write)
    • maximum size (number of elements, memory usage)

    Now imagine you want to let the user of your cache choose any of these options, and you use inheritance. You'll need 3 * 2 * 2 = 12 different classes:

    • LifoAfterReadNumberOfElementsBasedCache,
    • LifoAfterReadMemoryBasedCache,
    • etc.

    Each of the 4 LifoXxx classes will have to implement the same algorithm to implement the LIFO strategy. Same for the other ones.

    Implement it with the strategy pattern instead of inheritance, and you'll have a single Cache class, and 7 strategy classes (one for each strategy), that you can combine however you want, and without code duplication.

    And you can also let the user of your Cache define its own strategy, that you haven't anticipated, and let him combine it with other strategies without needing to create a whole lot of new subclasses.