如何在C++或JAVA中限制类的实例数?

Sat*_*dav 5 c++ java class object instance

我在一次采访中向我询问了这个问题,我试图无法回答这个问题,我希望在C++或JAVA中使用一段限制类的实例(对象)的代码.

Eri*_*ein 10

使用工厂.保留已释放实例数的私有静态计数器.不允许实例限制类的构造函数可见.


Rah*_*thi 5

static variableC++中尝试这样: -

struct myclass
{
  myclass()
  {
    if(count == N) { /*throw some exception here!*/ }
    ++count;
  }
  ~myclass()
  {
    --count;
  }
private:
  static std::size_t count = 0;
};
Run Code Online (Sandbox Code Playgroud)

每当创建一个对象时,count变量就会增加1.

在JAVA

示例实现可能是这样的: -

public class MyClass {
    private static final int LIMIT = 10; //Set this to whatever you want to restrict
    private static int count = 0;
    private MyClass() {}
    public static synchronized MyClass getInstance() {
        if (count < LIMIT) {
            MyClass myClass = new MyClass();
            count++;
            return myClass;
        } 
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)