vendredi 18 novembre 2022

Is it right to put data members in a C++ interface?

I'm trying to implement the strategy design pattern in C++, as shown in this following schematic: uml diagram

I would like to know, if it's correct to add data members in the interface ? If no, why ? In case if this implementation is correct. How to test is using google mock ?

I share with you the pseudo code of what I trying to accomplish :

#include <cassert>
#include <memory>

constexpr int maxCases = 7 * 5 * 3;

class IStrategy
{
public:
    IStrategy();
    ~IStrategy() = default;
    virtual void algorithm() = 0;
    int method1(const int x) const;
protected:
    int method2(const int x, const int y) const;

private:
    int* allCases{};
};

IStrategy::IStrategy() : allCases(new int[maxCases]) {}

int IStrategy::method2(const int x, const int y) const
{
    int result{};
    assert(sizeof(allCases) /sizeof(*allCases) <= maxCases);
    // ...
    return result;
}

int IStrategy::method1(const int x) const
{
    int result{};
    // ...
    return result;
}

class StrategyA : public IStrategy
{
public:
    virtual void algorithm() override;
};

void StrategyA::algorithm()
{
    int x{0};
    int y{0}; 
    // ...
    int nbrOfCases = method2(x, y);
    // ...
}

class StrategyB : public IStrategy
{
public:
    virtual void algorithm() override;
};

void StrategyB::algorithm()
{
    int x{0};
    int y{0}; 
    // ...
    int nbrOfCases = method2(x, y);
    // ...
}

class StrategyC : public IStrategy
{
public:
    virtual void algorithm() override;
};

void StrategyC::algorithm()
{
    int x{0};
    int y{0}; 
    // ...
    int nbrOfCases = method2(x, y);
    // ...
}

class Context
{
public:
    void setStrategy(IStrategy* stgy);
    void applyStrategy() const;
private:
    IStrategy* strategy;
};

void Context::setStrategy(IStrategy* stgy)
{
    strategy = stgy;
}
void Context::applyStrategy() const
{
    strategy->algorithm();

}

void clientCode()
{
    Context context;
    StrategyA strategyA;
    StrategyA strategyB;
    StrategyA strategyC;
    // ...
    context.setStrategy(&strategyA);
    context.applyStrategy();
    // ...
    context.setStrategy(&strategyB);
    context.applyStrategy();
    // ...
    context.setStrategy(&strategyC);
    context.applyStrategy();
    // ...
}

int main(int argc, const char* argv[])
{
    clientCode();
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire