Yes, singleton design pattern will be helpful for this kind of situation. We just need to do some modification in singleton class. We can restrict our java class for creating specified number of objects of it.
A singleton class is a class which always returns a single object at any time of application life cycle. To create a singleton class, we need to follow the singleton design pattern.
Steps required to implement a singleton class:
--------------------------------------------------------------------------------------
Step 1: Create a class variable which is basically a reference of it?s own class.
Step 2: Make the constructor private.
Step 3: Create a static method which returns a reference of it?s own class.
Step 4: In the method, check the class variable for null. if it is null create an instance of the class and assign to the class variable.
Now following is the sample code to return the specified no of objects of a class.
RestrictedClassForMultipleObjects.java:
-------------------------------------------------------------------------
public class RestrictedClassForMultipleObjects
{
private static RestrictedClassForMultipleObjects limitedNoOfObjectClass;
public static int noOfObject = 0;
private RestrictedClassForMultipleObjects() {
noOfObject++;
}
public static synchronized RestrictedClassForMultipleObjects getLimInstance()
{
if (noOfObject <3)
limitedNoOfObjectClass = new RestrictedClassForMultipleObjects();
return limitedNoOfObjectClass;
}
}
ObjectCreationTest.java:
----------------------------------------------
class ObjectCreationTest
{
public static void main(String args[])
{
RestrictedClassForMultipleObjects obj1 = RestrictedClassForMultipleObjects.getLimInstance();
RestrictedClassForMultipleObjects obj2 = RestrictedClassForMultipleObjects.getLimInstance();
RestrictedClassForMultipleObjects obj3 = RestrictedClassForMultipleObjects.getLimInstance();
RestrictedClassForMultipleObjects obj4 = RestrictedClassForMultipleObjects.getLimInstance();
RestrictedClassForMultipleObjects obj5 = RestrictedClassForMultipleObjects.getLimInstance();
System.out.println(obj1);
System.out.println(obj2);
System.out.println(obj3);
System.out.println(obj4);
System.out.println(obj5);
}
}
Compile and run ObjectCreationTest class and you will get 3 objects only and if you demand more it will return the third object each time..
7