How to limit the number of class instances in C ++ or JAVA?

The question was asked in an interview, I tried to think that I could not answer it, I need a piece of C ++ or JAVA code that limits the number of class instances (objects).

+4
source share
5 answers

Use factory. Keep a private static counter of the number of issued instances. Do not allow constructor visibility for your instance-restricted class.

+9
source

Try this with help static variablein C ++ : -

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

Whenever an object is created, the variable count is incremented by 1.

In 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;
    }
}
+4

Factory , , ?... Private
:

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, .
, ( ), contructor private, , Factory , , .
contructor , , .
,

+1

, . Singleton

, , (, singleton) .

x() null, factory 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/

+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

0
source

All Articles