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

工厂方法创建的对象应该从何处删除?

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

    创建对象的方式和位置 returnShapeType 是否删除?
    这是一个工厂方法演示程序。

    请出示密码。

    class Shape
    {
    public:
        Shape() {}
        virtual void print() {std::cout << "\nFrom shape print";}
    };
    
    class Triangle: public Shape
    {
    public:
        Triangle(){}
        virtual void print() {std::cout << "\nFrom triangle print";}
    };
    
    class Rectangle: public Shape
    {
    public:
        Rectangle(){}
        virtual void print() {std::cout << "\nFrom rect print";}
    };
    
    class CreateShapeObject
    {
    public:
        CreateShapeObject() {}
    
        Shape *returnShapeType( std::string arg )
        {
            if (arg == "Triangle")
                return new Triangle;
            else if (arg == "Rectangle")
                return new Rectangle;
        }
    };
    
    ////////////
    
    class EndDeveloper
    {
    public:
        CreateShapeObject obj;
    
        EndDeveloper()
        {
            Shape *p = obj.returnShapeType("Triangle");
            p->print();
    
            Shape *q = obj.returnShapeType("Rectangle");
            q->print();
    
    
        }
    };
    
    3 回复  |  直到 8 年前
        1
  •  2
  •   R Sahu    8 年前

    CreateShapeObject

    创建形状对象 ShapeObjectManager

        2
  •  6
  •   krisz    8 年前

    unique_ptr

    std::unique_ptr<Shape> returnShapeType(const std::string& arg)
    {
        if (arg == "Triangle")
            return std::make_unique<Triangle>();
        else if (arg == "Rectangle")
            return std::make_unique<Rectangle>();
        throw std::invalid_argument("Invalid shape");
    }
    

    auto

    auto shape = obj.returnShapeType("Triangle");
    

    shared_ptr 以下内容:

    std::shared_ptr<Shape> shape = obj.returnShapeType("Triangle");
    
        3
  •  2
  •   Yunnosch    8 年前

    new
    (是否通过工厂)负责 delete 也一样。

    推荐文章