I'm asked to implement an interface and I'm wondering what would be the best strategy to factorize the code as much as possible.
Here is the interface definition (I'm not supposed to change it):
#include <string>
class BaseIf
{
public:
virtual ~BaseIf() {}
virtual std::string getName() = 0;
};
class IntIf : public BaseIf
{
public:
virtual ~IntIf() {}
virtual int getValue() = 0;
};
class FloatIf : public BaseIf
{
public:
virtual ~FloatIf() {}
virtual float getValue() = 0;
};
I'll end up with IntImpl
(implementing IntIf
) and FloatImpl
(implementing FloatIf
). But I'm wondering where I should put any code common to those two classes (like the name
attribute management or any other stuff required by BaseIf
which is actually much bigger than in this MCVE).
If I create BaseImpl
(implementing BaseIf
's getName
function) with the common code, and have IntImpl
derive from it (and IntIf
), then I need to also implement getName
in it because it's reported as not implemented. ANd I also get double inheritance of BaseIf
...
I was wondering if Pimpl pattern would help, then IntImpl
would have a BaseImpl
object as attribute (and only derive from IntIf
), but then, again, I need to implement getName
in IntImpl
to "forward" the call to the BaseImpl
attribute. So as BaseIf
has actually many virtual functions this is just going to be a real pain to maintain.
Is there no smart solution/pattern making it possible to implement once only getName
in a common place? Or is it just the interface that is bad and should be reworked?
Aucun commentaire:
Enregistrer un commentaire