代码之家  ›  专栏  ›  技术社区  ›  Aquarius_Girl

这是写我工厂方法的最好方法吗

  •  0
  • Aquarius_Girl  · 技术社区  · 8 年前

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

    创建形状对象 这里是工厂方法吗?

    工厂方法的正确实现依据是什么 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;
                            ^
    
    1 回复  |  直到 8 年前
        1
  •  4
  •   catnip    8 年前

    我一点都不明白。

    工厂方法的目的是在不直接调用其构造函数的情况下创建派生类的实例。但是您的代码处于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 .

    推荐文章