我一点都不明白。
工厂方法的目的是在不直接调用其构造函数的情况下创建派生类的实例。但是您的代码处于catch-22的情况下——例如,
PaintRectangle
您首先需要有这样一个对象的现有实例!我希望你能看到这一切毫无进展。
尝试类似的方法:
class PaintShape
{
public:
static PaintShape *createShapeObject(std::string shape);
};
class PaintTriangle : public PaintShape
{
public:
PaintTriangle() { }
// ...
};
class PaintRectangle : public PaintShape
{
public:
PaintRectangle() { }
// ...
};
// This is our (*static*) factory method
PaintShape *PaintShape::createShapeObject(std::string shape)
{
if (shape == "triangle")
return new PaintTriangle;
if (shape == "rectangle")
return new PaintRectangle;
return nullptr;
};
然后你可以简单地做(例如):
std::string shape;
std::cout << "What shape would you like? ";
std::getline (std::cin, shape);
PaintShape *ps = PaintShape::createShapeObject (shape);
// ...
如果您有任何问题,请告诉我-请仔细阅读有关为什么的评论,严格地说,
createShapeObject()
应该返回
std::unique_ptr
.