Best method to implement an abstract factory pattern

前端 未结 2 1882
醉酒成梦
醉酒成梦 2021-01-20 05:15

Consider following code:

#include 


// =============================


class Shape{
public:
    virtual ~Shape(){};

    virtual void process         


        
相关标签:
2条回答
  • 2021-01-20 06:01

    Your factories are passing around ownership. There's another alternative to that aspect; instead of passing around ownership, you can make the factory own the objects:

       class Factory {
       public:
          ~Factory() { for(int i=0;i<vec.size();i++) delete vec[i]; }
          Shape &build_obj() {
             Shape *sh = new Triangle;
             vec.push_back(sh);
             return *sh;
           }
    
       private:
          void operator=(const Factory &);
          std::vector<Shape*> vec;
       };
    
    0 讨论(0)
  • 2021-01-20 06:07

    I think the most idiomatic modern C++ method is the one you mention in passing but ignore. Return a std::unique_ptr<Shape>.

    It is safe, clearly expresses ownership, supports polymorphism and doesn't need much code.

    class ShapeFactory {
    public:
      std::unique_ptr<Shape> create(){
        return std::make_unique<Triangle>();
      }
    };
    

    But I wouldn't want to claim it was the "best" method.

    Your PimplShape in option 3 is actually very similar to a unique_ptr just less generic or tested.

    0 讨论(0)
提交回复
热议问题