Subclass specific access in Factory pattern
I have a design based question where I want to avoid dynamic_cast but still want to know how to get to loose couplin开发者_开发技巧g.
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?
In an ideal design, publicly inherited classes have an "is a" relation and not an "is an extension of" relation in the sense that they may be extended but you don't notice it from the interface point of view. This is best achieved if you actually order objects to do something and you don't get/set them. In that case factories can just create what is needed and clients don't need to know the actual class (polymorphism).
This is not always possible/easy, so casting could be the solution, but you could argue that a factory may not be needed in that case (O_derived_X could create a Prod_X object itself).
精彩评论