I have a design based question where I want to avoid dynamic_cast but still want to know how to get to loose coupling.
class Prod { // Prod has lot of subclasses
public:
void method()
{//Some Implementation
}
};
class Prod_X : Prod
{
int special_variable;
public:
void method()
{//Override Base
}
void setSpecialVariable()
{//Set Special Variable
}
};
class Factory
{
public:
Prod* create(string &s)
{ if (s == "X") return new Prod_X; //And so on
};
};
class O
{
public:
Factory F; // Assume we are talking about a simple factory pattern
Prod* create(string &s)
{ p = F.create(s); return p;}
Prod* p;
};
// Issue is here on coupling and how to avoid dynamic_cast
// Inherited Prod member for O_derived_X is always Prod_X (Factory takes care of that)
class O_derived_X {
int special_variable;
public:
void setSpecialVariable()
{ // Need to set Prod_X Variable
Prod_X *px = dynamic_cast<Prod_X*>(p);
px->setSpecialVariable();
}
};
Two things
- I introduced the special_variable in Prod_X because it was an attribute of Prod_X and not Prod in general. Is this right?
- class O basically uses the interface of class Prod to do mostly everything. But, for this special variable, O_derived_X is interested in setting it correctly.
Could you suggest where I am going wrong? Or how can I refactor the code?