我的意图是在基类中创建一个空虚函数。在派生类中重新定义该函数,以便它们返回特定子类的对象。
createShapeObjects 是这里的工厂方法。
根据 GOF book,工厂方法的正确实现是什么? ?
事实.h
#ifndef FACTO
#define FACTO
class PaintShapes
{
public:
virtual PaintShapes createShapeObjects(string arg) {};
};
class PaintTriangle : public PaintShapes
{
public:
PaintTriangle() {}
virtual PaintShapes createShapeObjects(string arg)
{
std::cout << "ddd";
if (arg == "triangle")
return new PaintTriangle;
}
};
class PaintRectangle : public PaintShapes
{
public:
PaintRectangle() {}
virtual PaintShapes createShapeObjects(string arg)
{
std::cout << "eee";
if (arg == "rectangle")
return new PaintRectangle;
}
};
/////
// My class which wants to paint a triangle:
/////
class MyClass
{
public:
PaintShapes obj;
void MyPaint()
{
obj.createShapeObjects("triangle");
}
};
#endif // FACTO
主要.cpp
#include <iostream>
using namespace std;
#include "facto.h"
int main()
{
cout << "Hello World!" << endl;
MyClass obj;
obj.MyPaint();
return 0;
}
这给出了错误:
error: could not convert '(operator new(4u), (<statement>, ((PaintTriangle*)<anonymous>)))' from 'PaintTriangle*' to 'PaintShapes'
return new PaintTriangle;
^
最佳答案
这些我都不懂
工厂方法的目的是在不直接调用其构造函数的情况下创建派生类的实例。但是您的代码处于第 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
的评论.
关于c++ - 这是编写我的工厂方法的最佳方式吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50893358/