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

时间:2018-06-17 03:14:39

标签: c++ oop factory gang-of-four

我的目的是在基类中创建一个空的虚函数。在派生类中重新定义该函数,使它们返回特定子类的对象。

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

1 个答案:

答案 0 :(得分:4)

我不明白这一点。

工厂方法的目的是创建派生类的实例而不直接调用其构造函数。但是你的代码处于Catch-22状态 - 例如,要创建process.stdout,你需要首先拥有这样一个对象的现有实例!我希望你能看到这无处可去。

尝试这样的事情:

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); // ... 应该返回std::unique_ptr的原因的评论。