这是编写我的工厂方法的最佳方式吗

Is this the best way to write my factory method

我的意图是在基 class 中创建一个空虚函数。在派生的 classes 中重新定义该函数,使它们 return 特定子 class 的对象。

createShapeObjects这里是工厂方法

根据 GOF book,工厂方法的正确实现是什么?

facto.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

main.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;
                        ^

我一点都不明白。

工厂方法的目的是创建派生对象的实例 class 而无需直接调用其构造函数。但是您的代码处于 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() 应该 return 和 std::unique_ptr.

的评论