Reputation: 1862
I got a question in one of interview to create only n (Fixed number) instance of any bean. If more than n instances are tried to create at runtime then throw any exception or print a message. Thank in advance
Upvotes: 2
Views: 1526
Reputation: 41220
Its easy to control over object creation of beans by providing custom bean factory. Where you can configure restriction like fixed number of object creation.
Example Code.
Upvotes: 2
Reputation: 26981
You just need to manage how many instances are created, you can do this in same bean using a list and a not standard constructor, but I will use a factory pattern:
Gived this bean
class BeanTest {
String name;
protected BeanTest(String name) {
this.name = name;
}
@Override
public String toString() {
return this.name;
}
}
You create a Factory
like this (in same package!)
class BeanFactory {
private static final int LIMIT = 5;
private static List<BeanTest> list = new ArrayList<BeanTest>();
public static synchronized BeanTest getInstance(String name) {
if (list.size() < LIMIT) {
BeanTest beanTest = new BeanTest(name);
list.add(beanTest);
return beanTest;
}
System.out.println("Not giving instance");
return null;
}
}
Test:
public static void main(String[] args) {
BeanTest a1 = BeanFactory.getInstance("a1");
System.out.println(a1);
BeanTest a2 = BeanFactory.getInstance("a2");
System.out.println(a2);
BeanTest a3 = BeanFactory.getInstance("a3");
System.out.println(a3);
BeanTest a4 = BeanFactory.getInstance("a4");
System.out.println(a4);
BeanTest a5 = BeanFactory.getInstance("a5");
System.out.println(a5);
BeanTest a6 = BeanFactory.getInstance("a6");
System.out.println(a6);
}
OUTPUT:
a1
a2
a3
a4
a5
Not giving instance
null
NOTES:
getInstance
method of the bean constructor into the BeanTest
class itself and make constructor private instead
of protected
You can also make a method destroyInstance
or removeInstance
in order to make more dynamic the Factory
:
public static synchronized boolean removeInstance(BeanTest toRemove) {
if (list.contains(toRemove)) {
return list.remove(toRemove);
}
return false;
}
Upvotes: 1