我使用boost factory来创建产品,我想做的是为它的DoSomething()
调用不同的产品,但问题是我希望每个产品的返回值都不同,并且它们都是结构。我要ProductA->DoSomething(),那么它的返回值就是structA,对于ProductB->DoSomething(),它的返回值就是strucB。并且所有结构都从基础 struct
驱动,这可能吗?感谢您的解决方案,非常感谢!
最佳答案
您可以声明基础 struct ReturnType
,它将定义基础方法和变量。然后您就可以毫无问题地创建产品。
struct ReturnType
{
virtual std::string getName(){}
};
struct MarsType : ReturnType
{
std::string specialMethod()
{
return "MARS";
}
};
struct SnikersType : ReturnType
{
std::string specialMethod2()
{
return "SNIKERS";
}
};
class Product
{
public:
virtual ReturnType* doSomething()=0;
};
class SnikersProduct : public Product
{
public:
ReturnType* doSomething()
{
return static_cast<ReturnType*>(&value);
}
private:
SnikersType value;
};
class MarsProduct : public Product
{
public:
ReturnType* doSomething()
{
return static_cast<ReturnType*>(&value);
}
private:
MarsType value;
};
class Creator
{
public:
virtual Product* createProduct()=0;
};
class SnikersCreator : public Creator
{
public:
Product* createProduct()
{
return new SnikersProduct();
}
};
class MarsCreator : public Creator
{
public:
Product* createProduct()
{
return new MarsProduct();
}
};
int main()
{
std::vector<Creator*> creators;
creators.push_back(new MarsCreator());
creators.push_back(new SnikersCreator());
Product* mars = creators[0]->createProduct();
Product* snikers = creators[1]->createProduct();
std::cout<<"mars product returns "<<dynamic_cast<MarsType*>(mars->doSomething())->specialMethod()<<std::endl;
std::cout<<"snikers product returns "<<dynamic_cast<SnikersType*>(mars->doSomething())->specialMethod2()<<std::endl;
return 0;
}
输出是:
mars product returns MARS
snikers product returns SNIKERS
关于c++ - 以不同产品的返回值(value) boost 工厂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13029794/