Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

The question was asked to me in an interview, i tried to think could not answer it, i want a piece of Code either in C++ or JAVA that restricts number of instance ( objects ) of a class.

like image 229
Satish Yadav Avatar asked Sep 26 '13 19:09

Satish Yadav


People also ask

How do I limit the number of instances of a class?

By making our constructor private and then creating a visible constructor method, we can limit the number of instance creations (like we do in singleton design pattern) or recycle instances or other construction-related tasks. Doing new x() never returns null, but using the factory pattern, you can return null.

How do you restrict a class in Java?

1.3 Steps to create singleton class in Java:Create INSTANCE of same class by instantiating class & this INSTANCE should be with private & static modifier. Provide public static method that returns same INSTANCE of class every time. Finally, create private constructor so that no-one create object from outside of class.

How do I restrict the number of objects created in C++?

You can add a static member that will be the counter of the class instances. When the counter exceeds 10, you throw an exception (runtime error) and the job is done. Save this answer.


4 Answers

Use a factory. Keep a private static counter of the number of instances released. Don't allow the constructor for your instance-limited class to be visible.

like image 175
Eric Stein Avatar answered Sep 29 '22 08:09

Eric Stein


Try like this using a static variable in C++:-

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

Whenever a object is created then the count variable is incremented by 1.

In JAVA

A sample implementation could be like this:-

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;
    }
}
like image 41
Rahul Tripathi Avatar answered Sep 29 '22 07:09

Rahul Tripathi


Yes we can restrict instances of class upto some specific limit. It is just an enhancement to Singleton Design Pattern

By making our constructor private and then creating a visible constructor method, we can limit the number of instance creations (like we do in singleton design pattern) or recycle instances or other construction-related tasks.

Doing new x() never returns null, but using the factory pattern, you can return null.

Here is the Java implementation for the same :

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

Output

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

output may vary based on your allocated JVM memory.

Reference : http://codepumpkin.com/use-private-constructor-java/

like image 22
Abhi Andhariya Avatar answered Sep 29 '22 07:09

Abhi Andhariya


The correct answer is By using Factory Methods and if question was how to do this?...By making constructor Private
A very simple example is:

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

Here the output will be 20 20 since both reference are pointing the same object.
Actually object is not made unless contructor is called(thats why its called as constructor) and if we make the contructor private then we can restrict the creation of object and then with factory methods we can control the creation as we want as in this case it only allows creation of 1 object.
It will call the contructor only if no objects are created for the class and after that it will just send the reference.
Hope this helps

like image 23
Nawed Shaikh Avatar answered Sep 29 '22 07:09

Nawed Shaikh