繁体   English   中英

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

[英]how to restrict number of instances of a class in C++ or JAVA?

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

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

C ++中使用static variable尝试这样: -

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;
    }
}

是的,我们可以将类的实例限制到某个特定限制。 它只是Singleton Design Pattern的增强功能

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

执行新的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/

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

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个对象。
只有在没有为类创建对象时才会调用构造函数,之后它将只发送引用。
希望这可以帮助

一个非常简单的解决方

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM