How to set data members of derived product class in factory design pattern?
class Factory
{
public:
product* Create(int type)
{
switch (type)
{
case 1:
return new product1;
break;
case 2:
return new product2;
break;
}
}
};
class product
{
int a;
public :
product();
product(int a);
void seta (int a);
};
class product1:public product
{
int b;
public:
product1();
product1(int a,int b):product(a), b(b) {}
void setb (int b);
};
class product2:public product
{
int c;
public:
product2();
product2(int a, int c):product(a), c(c) {}
void setc (int c);
};
\\ client code
void main()
{
Factory f;
product* p = f.create(1); // product1 created
p->seta(2);
// now how to set value b of product1
}
Note: if I down cast the p to p1 then there will be no point of using factory. Hence don't know how to use it.
EDIT : set method added for product, product1, product2. How to set value for b in main if product1 created using factory?
Ideally
bwould be set by theFactoryduringcreate. Is there any reason why that is not possible?Failing that, you will probably have to set
bvia avirtualmethod onProduct. Preferably via avirtualmethod that makes sense in the context of allProducts.Where does the value of
bcome from? For example, say the value comes from a file, it might make sense to have a virtual methodProduct::setThingsFromFile(string file). Override thisvirtualmethod inProduct1to setbfrom the file.It might be a bit overkill, but you could consider using the Visitor Pattern and set
bin theConcreteVisitor::visit(Product1& product)method.As a last resort you could add a
virtual void Product::setB(int b)that is a no-op for mostProducts and only actually does anything forProduct1but it's not a good idea generally and is a good way of making a mess ofProduct.Remember that the point of a Factory is that the client code shouldn't need to know what
Productit is working with so if it needs to know it has aProduct1to setbthen there is not much point using a Factory.