防止在其工厂方法之外实例化对象

5 c++ oop factory-pattern

假设我有一个带有工厂方法的类

class A {
public:
  static A* newA()
  {
    // Some code, logging, ...
    return new A();
  }
}
Run Code Online (Sandbox Code Playgroud)

是否可以使用a来阻止此类对象的实例化new,以便工厂方法是创建对象实例的唯一方法?

Oli*_*rth 8

当然; 只是使构造函数私有(如果这是一个基类,则受保护):

class A {
public:
  static A* newA()
  {
    // Some code, logging, ...
    return new A();
  }

private:
  A() {}  // Default constructor
};
Run Code Online (Sandbox Code Playgroud)

如果需要,您还应该将复制构造函数设置为private/protected.

和往常一样,您应该强烈考虑返回智能指针而不是原始指针,以简化内存管理问题.