In this program we prevent for creating number of instance in Singleton class.here we create a constructor for increment. from getInstance method we count the object.
public class SingletonTest {
private static SingletonTest h = null;
static int count = 0;
public SingletonTest() {
count++;
}
public static SingletonTest getInstance() {
if (count < 2) {
h = new SingletonTest();
}
return h;
}
public static void main(String[] args) {
SingletonTest s1 = SingletonTest.getInstance();
System.out.println(s1.hashCode());
SingletonTest s2 = SingletonTest.getInstance();
System.out.println(s2.hashCode());
SingletonTest s3 = SingletonTest.getInstance();
System.out.println(s3.hashCode());
}
}
Output :-
366712642
1829164700
1829164700