+ 3
Can anybody explain me what Singleton class is?
4 Réponses
+ 4
The Singleton's purpose is to control object creation, limiting the number of objects to one only. Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields. Singletons often control access to resources such as database connections or sockets.
+ 1
A singleton pattern design returns only one instance of the class.
This could be archived by making class constructor private and creating a static method that returns only one instance.
Ex:
class Single{
private int age;
private static Single onlyOne;
private Single() {}
public static Single get(int age){
if(onlyOne == null ){
onlyOne = new Single();
}
onlyOne.age = age;
return onlyOne;
}
public void show(){
if(onlyOne != null) {
System.out.println(age) ;
}
}
}
public class Program
{
public static void main(String[] args) {
Single s = Single.get(26);
s.show();
}
}
+ 1
similar to singleton set in maths
singleton classes have only one instance / object
0
Singleton class is the class which will instantiate only one object per JVM and it returns same object whenever required.