5

这个问题是在一次采访中向我提出的,我试图认为无法回答,我想要一段 C++ 或 JAVA 中的代码来限制类的实例(对象)的数量。

4

5 回答 5

10

使用工厂。保留已释放实例数的私有静态计数器。不要让实例受限类的构造函数可见。

于 2013-09-26T19:11:32.163 回答
6

static variableC++中使用 a 尝试这样的操作:-

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

每当创建一个对象时,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;
    }
}
于 2013-09-26T19:13:05.933 回答
2

是的,我们可以将类的实例限制到某个特定的限制。它只是对单例设计模式的增强

通过将构造函数设为私有,然后创建可见的构造函数方法,我们可以限制实例创建的数量(就像我们在单例设计模式中所做的那样)或回收实例或其他与构造相关的任务。

执行 new x() 永远不会返回 null,但使用工厂模式,您可以返回 null。

这是相同的Java实现:

public class LimitObjectCreationTest {

        public static void main(String[] args) {

        LimitClass obj;
        int i=1;
        while(i<=20)
        {
            obj = LimitClass.getLimInstance();
            i++;
        }
      }
}


class LimitClass {

    /**
     * count of alive instances in JVM  
     */
    public static int objCount = 0;

    /**
     * private constructor
     * increases the objCount static variable on every object creation
     */
    private LimitClass(){
        objCount++;
        System.out.println("instance " + objCount + " created");
    }

    /**
     * static factory method to return LimitClass instance
     * @return instance of LimitClass if not reached to threshold, else returns null
     */
    public static synchronized LimitClass getLimInstance() {
        if(objCount < 3 ){
            return new LimitClass();
        }
        System.out.println("Instance Limit reached. Can not create new Object");
        System.gc();
        return null;
    }

    /**
     * decreases the objCount static variable when JVM runs garbage collection
     * and destroys unused instances
     */
    @Override
    public void finalize()
    {
        System.out.println("Instance destroyed");
         objCount--;
    }
}

输出

instance 1 created
instance 2 created
instance 3 created
Instance Limit reached. Can not create new Object
Instance Limit reached. Can not create new Object
Instance destroyed
Instance Limit reached. Can not create new Object
Instance destroyed
instance 3 created
Instance destroyed
instance 2 created
instance 3 created
Instance Limit reached. Can not create new Object
Instance Limit reached. Can not create new Object
Instance destroyed
Instance Limit reached. Can not create new Object
Instance destroyed
instance 3 created
Instance destroyed
instance 3 created
instance 3 created
Instance Limit reached. Can not create new Object
Instance Limit reached. Can not create new Object
Instance destroyed
Instance Limit reached. Can not create new Object
Instance destroyed
Instance destroyed
instance 1 created
instance 2 created

输出可能会根据您分配的 JVM 内存而有所不同。

参考: http ://codepumpkin.com/use-private-constructor-java/

于 2017-07-09T11:27:23.657 回答
1

正确的答案是通过使用工厂方法,如果问题是如何做到这一点?...通过将构造函数设为私有
一个非常简单的例子是:

class SingletonClass{ //i.e class with only one instance
private int a;
private SingletonClass() // here you see constructor is private
{}
private static SingletonClass ref; // this is static reference of the class
public static SingletonClass getInstance(){ //this is the factory method
if(ref==null)
ref=new SingletonClass();
return ref;
}
public void setA(int a){
this.a = a;
}
public int getA(){
return a;
}
}
class Demo{
public static void main(String []s){
SingletonClass s,p; // 2 references for the SingletonClass
s = new SingletonClass(); /*this will generate compile time error since contructor is                        private */
s = SingletonClass.getInstance();
p = SingletonClass.getInstance();
s.setA(10);
p.setA(20);
System.out.println(s.getA()+" "+p.getA());
}
}

这里的输出将是20 20因为两个引用都指向同一个对象。
实际上,除非调用构造函数(这就是为什么它被称为构造函数),否则不会生成对象,如果我们将构造函数设为私有,那么我们可以限制对象的创建,然后使用工厂方法,我们可以根据需要控制创建,在这种情况下它只允许创建 1 个对象。
只有当没有为类创建对象时,它才会调用构造函数,之后它只会发送引用。
希望这可以帮助

于 2013-09-30T19:49:29.143 回答
0

一个非常简单的解决方案

class XYZ {
private statuc XYZ[] instance;
public XYZ[] getInstance(){

if (instance == null) {

instance = new XYZ[4] ; // here I am restricted to make only 4 inxtance

}// if ends here
return instance;

}// getinstance() ends here

}// class ends here

使用此功能,我们可以根据需要添加其他方法和变量

于 2013-12-11T08:38:54.933 回答